R:如果多个列相等,则按行合并数据[重复]

问题描述 投票:0回答:1

我有一个看起来像这样的data.frame:

table <- read.table(textConnection("W\tX\tY\tZ
                               A\t2\t3\t4
                               A\t2\t3\t6
                               A\t1\t2\t3
                               C\t3\t2\t1
                               B\t1\t3\t4
                               B\t1\t2\t2"),header=T)

我想合并第1列到第3列(W,X,Y)的相等行,然后保留第4列(Z)的所有值。结果应如下所示:

W     X     Y    Z
A     2     3    4,6
A     1     2    3
C     3     2    1
B     1     3    4
B     1     2    2

你看,前两列已经合并,其余的没有。

r merge row condition equals
1个回答
1
投票

您可以使用dplyr包对数据进行分组和汇总

library(dplyr)

group_by(table, W, X, Y) %>%
 summarise(Z=paste0(Z, collapse=','))

此操作的结果看起来像您想要的:

# A tibble: 5 x 4
# Groups:   W, X [?]
       W     X     Y     Z
  <fctr> <int> <int> <chr>
1      A     1     2     3
2      A     2     3   4,6
3      B     1     2     2
4      B     1     3     4
5      C     3     2     1
© www.soinside.com 2019 - 2024. All rights reserved.