R - Group data but apply different functions to different columns

data.table, grouping, plyr, r

Solution

Using `data.table`:

require(data.table)
dt <- data.table(data, key="ID")
dt[, list(type=type[1], isDesc=sum(isDesc), 
                  isImage=sum(isImage)), by=ID]

#    ID type isDesc isImage
# 1:  1    1      1       2
# 2:  4    2      1       1
# 3:  6    1      1       1

Using `plyr`:

ddply(data , .(ID), summarise, type=type[1], isDesc=sum(isDesc), isImage=sum(isImage))
#   ID type isDesc isImage
# 1  1    1      1       2
# 2  4    2      1       1
# 3  6    1      1       1

Edit: Using `data.table`'s `.SDcols`, you can do this in case you've too many columns that are to be summed, and other columns to be just taken the first value.

dt1 <- dt[, lapply(.SD, sum), by=ID, .SDcols=c(3,4)]
dt2 <- dt[, lapply(.SD, head, 1), by=ID, .SDcols=c(2)]
> dt2[dt1]
#    ID type isDesc isImage
# 1:  1    1      1       2
# 2:  4    2      1       1
# 3:  6    1      1       1

You can provide column names or column numbers as arguments to .SDcols. Ex: `.SDcols=c("type")` is also valid.

Problem

I'd like to group this data but apply different functions to some columns when grouping. ``` ID type isDesc isImage 1 1 1 0 1 1 0 1 1 1 0 1 4 2 0 1 4 2 1 0 6 1 1 0 6 1 0 1 6 1 0 0 ``` I want to group by `ID`, columns `isDesc` and `isImage` can be summed, but I would like to get the value of type as it is. `type` will be the same through the whole dataset. The result should look like this: ``` ID type isDesc isImage 1 1 1 2 4 2 1 1 6 1 1 1 ``` Currently I am using ``` library(plyr) summarized = ddply(data, .(ID), numcolwise(sum)) ``` but it simply sums up all the columns. You don't have to use `ddply` but if you think it's good for the job I'd like to stick to it. `data.table` library is also an alternative

Original source