提迪尔在多个列上使用了split_rows [英] tidyr use separate_rows over multiple columns
问题描述
我有一个data.frame,其中某些单元格包含逗号分隔值的字符串:
I have a data.frame where some cells contain strings of comma separate values:
d <- data.frame(a=c(1:3),
b=c("name1, name2, name3", "name4", "name5, name6"),
c=c("name7","name8, name9", "name10" ))
我想将每个名称都拆分成自己的单元格的字符串分开.
I want to separate those strings where each name is split into its own cell. This is easy with
tidyr::separate_rows(d, b, sep=",")
如果一次只完成一列.但是我不能同时对"b"和"c"两列执行此操作,因为这要求每个字符串中的名称数相同.不用写
if it is done for one column a time. But I can't do this for both columns "b" and "c" at the same time, since it requires that the number of names in each string is the same. Instead of writing
tidyr::separate_rows(d, b, sep=",")
tidyr::separate_rows(d, c, sep=",")
有没有一种方法可以做到这一点,例如与申请?像
Is there a way to do this in a one-liner, for e.g. with apply? Something like
apply(d, 2, separate_rows(...))
不确定如何将参数传递给separate_rows()
函数.
Not sure how to pass the arguments to the separate_rows()
function.
推荐答案
您可以使用管道.请注意,sep = ", "
是自动检测到的.
You can use a pipe. Note that sep = ", "
is automatically detected.
d %>% separate_rows(b) %>% separate_rows(c)
# a b c
# 1 1 name1 name7
# 2 1 name2 name7
# 3 1 name3 name7
# 4 2 name4 name8
# 5 2 name4 name9
# 6 3 name5 name10
# 7 3 name6 name10
注意:使用tidyr版本0.6.0,其中%>%
运算符包含在软件包中.
Note: Using tidyr version 0.6.0, where the %>%
operator is included in the package.
更新:使用@doscendodiscimus注释,我们可以使用for()
循环并在每次迭代中重新分配d
.这样,我们可以拥有尽可能多的列.我们将使用列名称的字符向量,因此我们需要切换到标准评估版separate_rows_
.
Update: Using @doscendodiscimus comment, we could use a for()
loop and reassign d
in each iteration. This way we can have as many columns as we like. We will use a character vector of column names, so we'll need to switch to the standard evaluation version, separate_rows_
.
cols <- c("b", "c")
for(col in cols) {
d <- separate_rows_(d, col)
}
提供更新的d
a b c
1 1 name1 name7
2 1 name2 name7
3 1 name3 name7
4 2 name4 name8
5 2 name4 name9
6 3 name5 name10
7 3 name6 name10
这篇关于提迪尔在多个列上使用了split_rows的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!