Split columns in dataframe with NA

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

    You can try a tidyverse as well

    library(tidyverse)
    df %>%
      rownames_to_column() %>% 
      separate_rows(FOO, sep="[|]") %>% 
      mutate(L=factor(FOO, labels = paste0("X",1:length(unique(FOO))))) %>% 
      spread(L, FOO) %>% 
      select(-1)
        X1   X2   X3
    1    A    B    C
    2    A    B 
    3     B    C
    4    A  
    5      C
    

    It is also generally working e.g. df <- data.frame(FOO = c('A|B|C', 'A|B', 'B|C', 'A', 'C', 'B|D|F')). In addition you can set the levels e.g. B>C>A by yourself using levels = c("B", "C", "A") in the factor function in the mutate step.

提交回复
热议问题