Separate a column of a dataframe in undefined number of columns with R/tidyverse [duplicate]

对着背影说爱祢 提交于 2019-12-02 13:38:25

问题


I have to import a table that look like as the following dataframe:

> df = data.frame(x = c("a", "a.b","a.b.c","a.b.d", "a.d"))
> df
      x
1  <NA>
2     a
3   a.b
4 a.b.c
5 a.b.d
6   a.d

I'd like to separate the first column in one or more columns based one how many separator I'll find.

The output should lool like this

> df_separated
  col1 col2 col3
1    a <NA> <NA>
2    a    b <NA>
3    a    b    c
4    a    b    d
5    a    d <NA>

I tried to use the separate function in tidyr but I need to specify a priori how many outoput columns I need.

Thank you very much for your help


回答1:


You can first count the number of columns it can take and then use separate.

nmax <- max(stringr::str_count(df$x, "\\.")) + 1
tidyr::separate(df, x, paste0("col", seq_len(nmax)), sep = "\\.", fill = "right")

#  col1 col2 col3
#1    a <NA> <NA>
#2    a    b <NA>
#3    a    b    c
#4    a    b    d
#5    a    d <NA>


来源:https://stackoverflow.com/questions/56356632/separate-a-column-of-a-dataframe-in-undefined-number-of-columns-with-r-tidyverse

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!