使用 R/tidyverse 在未定义的列数中分隔数据框的列 [英] Separate a column of a dataframe in undefined number of columns with R/tidyverse
本文介绍了使用 R/tidyverse 在未定义的列数中分隔数据框的列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我必须导入一个类似于以下数据框的表:
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.
输出应该像这样
> 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>
我尝试在 tidyr 中使用单独的函数,但我需要先验指定我需要多少输出列.
I tried to use the separate function in tidyr but I need to specify a priori how many outoput columns I need.
非常感谢您的帮助
推荐答案
可以先统计它可以占用的列数,然后使用separate
.
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>
这篇关于使用 R/tidyverse 在未定义的列数中分隔数据框的列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文