0

I have a data.frame that looks something like this:

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)

I want to merge the rows that are equal for columns 1 to 3 (W,X,Y) and then keep all the values of column 4 (Z). The result should look like this:

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

You see, the first two columns got merged, the rest didn't.

ChrM
  • 61
  • 3
  • 12

1 Answers1

1

You could use the dplyr package to group and summarise the data

library(dplyr)

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

The result of this operation looks like what you want:

# 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
Frank
  • 98
  • 5