根据分组变量将值粘贴在一起 [英] Paste values together based on a grouping variable

查看:39
本文介绍了根据分组变量将值粘贴在一起的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是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 IDtogether

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆