Split columns in dataframe with NA

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

    Simply do:

    splt <- strsplit(as.character(df$FOO),"\\|")
    all_val <- sort(unique(unlist(splt)))
    t(sapply(splt,function(x){all_val[!(all_val %in% x)]<-NA;all_val}))
    
    
    #     [,1] [,2] [,3]
    #[1,] "A"  "B"  "C" 
    #[2,] "A"  "B"  NA  
    #[3,] NA   "B"  "C" 
    #[4,] "A"  NA   NA  
    #[5,] NA   NA   "C" 
    

    data:

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

    Please note:

    My version is base:: (no libraries needed) and general:

    It would also work with:

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

提交回复
热议问题