根据分组变量将值粘贴在一起

C78*_*C78 2 r dataframe

我是 R 编程新手,正在尝试重新排列数据框。基本上我有一个包含 ID 的列和一个包含 y 字符串值的列。每个 ID 有多个 y,因此多行具有相同 ID 但不同 y。我只想为每个 ID 获取一行,并将所有 y 值连接到另一列的同一单元格中。有没有一个函数可以做到这一点?

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
Run Code Online (Sandbox Code Playgroud)

use*_*650 5

您可以aggregate()在此处将每个元素paste()一起使用unique()ID

aggregate(y ~ ID, unique(dat), paste, collapse = ", ")
Run Code Online (Sandbox Code Playgroud)

数据

dat <- read.table(text="ID  y
A   apple
B   pear
C   grape
A   grape
B   apple
C   grape", header=T)
Run Code Online (Sandbox Code Playgroud)

编辑添加了collapse@pdb评论的参数并更改unique了@DavidArenburg

  • 我认为您可以在每个聚合中跳过运行“unique”,而只执行“aggregate(y ~ ID, unique(dat), Paste, Collapse = ", ")”,以提高效率和简单性。 (2认同)