简体   繁体   English

在R中将多行转换为单行

[英]Convert multiple rows to single row in R

Original table: 原始表格:

ID------REMARK

1------ A

2------ B

1-------AG

3-------V

2-------BS

1--------E

4--------B

4--------BS

Required table: 必填表:

ID......REMARK

1-------A,AG,E

2-------B,BS

3-------V

4-------B,BS

and then list according to frequently occurring sequences: 然后根据频繁出现的顺序列出:

REMARK......OCCURRENCES


A,AG,E-------1

B,BS---------2

V -----------1

Here's an approach. 这是一种方法。 dat is the name of your data frame: dat是数据框的名称:

res1 <- aggregate(REMARK ~ ID, dat, paste, collapse = ",")
#   ID REMARK
# 1  1 A,AG,E
# 2  2   B,BS
# 3  3      V
# 4  4   B,BS

table(res1$REMARK)
# 
# A,AG,E   B,BS      V 
#      1      2      1 

Here is a plyr solution: 这是一个plyr解决方案:

library(plyr)
dt.agg <- ddply( dt, .(ID), summarise, Remark = paste( REMARK, collapse = ",", sep = "" )  )
ddply( dt.agg, .(Remark), nrow )

  Remark V1
1 A,AG,E  1
2   B,BS  2
3      V  1

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM