根据分组变量将值粘贴在一起 [英] Paste values together based on a grouping variable
问题描述
我是R编程的新手,我正在尝试重新排列数据框。基本上,我有一列具有ID和一列具有y字符串值。每个ID超过一个y,因此具有相同ID但不同y的多行。我想每个ID仅获得一行,并将所有y值串联在另一列的同一单元格中。有功能吗?
I'm new at R programing and Im trying to rearrange a data frame. Basically I have a column with IDs and a column with y string values. There's more than one y per ID so multiple rows with the same ID but different y. I want to get only one row per ID and all the y value concatenated in the same cell in the other column. Is there a function that does that ?
original data
ID y
A apple
B pear
C grape
A grape
B apple
C grape
transformed data
ID y
A apple,grape
B pear, apple
C grape
推荐答案
您可以在此处使用 aggregate()
来 paste()
unique()每个
ID 总计的
元素
You can use aggregate()
here to paste()
the unique()
elements for each ID
together
aggregate(y ~ ID, unique(dat), paste, collapse = ", ")
数据
dat <- read.table(text="ID y
A apple
B pear
C grape
A grape
B apple
C grape", header=T)
编辑添加了折叠
参数re @pdb注释并更改了 unique
re @DavidArenburg
EDIT added collapse
argument re @pdb comment and changed unique
re @DavidArenburg
这篇关于根据分组变量将值粘贴在一起的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!