I am looking for an efficient solution to add subtotals for every column in a new row for each category in the column 'id'. I am able to achieve the desired output by using the code below, but this approach is not efficient for large datasets. Is it possible to accomplish this using datatables?
Thanks!
data <- data.frame(id = c("a","b","a","b","c","c","c","a","a","b"),
total = c(1,2,3,4,2,3,4,2,3,4),
total2 = c(2,3,4,2,3,4,5,6,4,2),
total3 = c(2,3,4,5,6,3,2,3,4,5))
data_new <- data.frame(id = character(), total = numeric(), total2 =
numeric(), total3 = numeric())
for (i in unique(data$id)){
subset <- data[data$id == i,]
subtotals <- data.frame(id = i, total = sum(subset$total), total2 =
sum(subset$total2), total3 = sum(subset$total3))
subset <- rbind(subset,subtotals)
data_new <- rbind(data_new, subset)
}
data_new