0

Consider the following data frame:

d <- data.frame(a = c(01,02,01),
                b = c(101,101,101),
                c = c(101,147,101),
                d = c(100,200,500))

I want to merge the rows after column c, if the first three cell is equal. That is, I want to get the final data frame:

    a   b    c    d  
1   01  101  101  600
2   02  101  147  200

That is, the value for column d has been merged for row 1 and 3, since they have the same value for the first three cell. How do I do that in R?

Michael
  • 485
  • 1
  • 9

1 Answers1

2

like this?

library( data.table )

#make d a data.table
setDT( d )
#summarise
d[, .(d = sum(d) ), by = .(a,b,c) ]

#    a   b   c   d
# 1: 1 101 101 600
# 2: 2 101 147 200
Wimpel
  • 16,956
  • 1
  • 15
  • 34
  • Thanks! What if I have multiple columns that I want to merge (consider my data frame was this and I want to merge d and e based on a, b and c): d – Michael Apr 30 '20 at 07:36
  • 1
    @Michael Using `dplyr` , `d %>% group_by(a, b, c) %>% summarise_at(vars(d:e), sum)` Or in `data.table` `d[, lapply(.SD, sum), .SDcols = d:e, .(a, b, c)]` – Ronak Shah Apr 30 '20 at 08:28