Split columns in dataframe with NA

前端 未结 5 2507
心在旅途
心在旅途 2021-02-20 05:16

I have a df like this:

df <- data.frame(FOO = c(\'A|B|C\', \'A|B\', \'B|C\', \'A\', \'C\'))

> df
    FOO
1 A|B|C
2   A|B
3   B|C
4     A
5            


        
5条回答
  •  南旧
    南旧 (楼主)
    2021-02-20 05:29

    Overlooked that OP asked for a base R solution. Please try @AndreElrico's, @r.user.05apr's or @milan's solutions.


    This can be done with cSplit_e from the splitstackshape package:

    library(splitstackshape)
    cSplit_e(
      data = df,
      split.col = "FOO",
      sep = "|",
      mode = "value",
      type = "character",
      fill = " ",
      drop = TRUE
    )
    #  FOO_A FOO_B FOO_C
    #1     A     B     C
    #2     A     B      
    #3           B     C
    #4     A            
    #5                 C
    

    Does also work in case of the following df (see OP's comment above).

    (df1 <- data.frame(FOO = c('A|B|C', 'A|B', 'B|C', 'A', 'C', 'B|D|F')))
    #    FOO
    #1 A|B|C
    #2   A|B
    #3   B|C
    #4     A
    #5     C
    #6 B|D|F
    
    cSplit_e(df1, "FOO", "|", "value",  "character", TRUE, fill = " ")
    #  FOO_A FOO_B FOO_C FOO_D FOO_F
    #1     A     B     C            
    #2     A     B                  
    #3           B     C            
    #4     A                        
    #5                 C            
    #6           B           D     F
    

提交回复
热议问题