Split columns in dataframe with NA

前端 未结 5 2492
心在旅途
心在旅途 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:43

    In base R:

    df <- data.frame(FOO = c('A|B|C', 'A|B', 'B|C', 'A', 'C'))
    
    dummy <- strsplit(as.character(df$FOO), "[|]")
    want <- data.frame(values = unlist(dummy),
                       ids = rep(1:length(dummy), unlist(lapply(dummy, length))), 
                       stringsAsFactors = FALSE)
    
    library(reshape2)
    want <- dcast(want, ids ~ values, value.var = "values", fill = " ")[, -1] # first col removed
    names(want) <- paste0("X", seq_along(unique(unlist(dummy)))) 
    want
    # X1 X2 X3
    #1  A  B  C
    #2  A  B   
    #3     B  C
    #4  A      
    #5        C
    

提交回复
热议问题