R中的折叠列

詹姆斯·万豪

我已尽力进行了搜索,部分问题是我真的不确定要问什么。这是我的数据,以及我希望如何结束:

现在:

john    a Yes
john    b No
john    c No
Rebekah a Yes
Rebekah d No
Chase   c Yes
Chase   d No
Chase   e No
Chase   f No

我希望它是:

john     a,b,c    Yes
Rebekah  a,d      Yes
Chase    c,d,e,f  Yes

请注意,当第三列是第一列中具有特定值的第一行时,它表示是。第三行不是必需的,我只是在使用它,以为我会尝试使用ifandfor语句来完成所有操作,但是我认为这样效率很低。有什么办法可以有效地完成这项工作?

Veerendra Gadekar

另一个选择是(使用@bgoldst提到的数据)

library('dplyr')

out = df %>% 
      group_by(a) %>% 
      summarize(b = paste(unique(c(b)), collapse=","), c = "yes")

#> out
#Source: local data frame [3 x 3]

#        a       b   c
#1   Chase c,d,e,f yes
#2 Rebekah     a,d yes
#3    john   a,b,c yes

使用 data.table

out = setDT(df)[, .(b = paste(unique(b),  collapse=','), c = "yes"), by = .(a)]

#> out
#         a       b   c
#1:    john   a,b,c yes
#2: Rebekah     a,d yes
#3:   Chase c,d,e,f yes

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章