Reputation: 690
I am trying to address a few troublesome rows in a dataframe in R. My recourse is to simply add them together, consoldiating two rows into 1. So for example if I had a 100 rows with X columns, I would have 99 rows with X columns after the operation. Ideally I would just pass two row numbers and they would be combined. I would want to add each value for every column like a matrix operation almost. How can I do this?
Upvotes: 1
Views: 3471
Reputation: 269644
Add the two rows together overwriting the second row and then remove the first row.
combine_rows <- function(data, row1, row2) {
data[row2, ] <- data[row1, ] + data[row2, ]
data[-row1, ]
}
# test using builtin data frame, BOD
BOD
## Time demand
## 1 1 8.3
## 2 2 10.3
## 3 3 19.0
## 4 4 16.0
## 5 5 15.6
## 6 7 19.8
combine_rows(BOD, 2, 3)
## Time demand
## 1 1 8.3
## 3 5 29.3 <-- this row is the sum of original rows 2 and 3
## 4 4 16.0
## 5 5 15.6
## 6 7 19.8
Upvotes: 3