Let's say I have the following data.table in R:
require(data.table)
dt <- data.table(ID = paste0("x", 1:5),
TV.Show=c("Farscape", "Farscape", "Star Trek", "Doctor Who", "Doctor Who"),
Date = seq(as.Date("2014/01/01"), as.Date("2014/01/05"), "days"),
Ratings.North = c(1.1, 0.9, 4.8, 3.4, 5.5),
Ratings.South= c(0.1, NA, 1.8, 3.1, 3.5))
setkey(dt, "TV.Show")
dt
# ID TV.Show Date Ratings.North Ratings.South
# x4 Doctor Who 2014-01-04 3.4 3.1
# x5 Doctor Who 2014-01-05 5.5 3.5
# x1 Farscape 2014-01-01 1.1 0.1
# x2 Farscape 2014-01-02 0.9 NA
# x3 Star Trek 2014-01-03 4.8 1.8
I would like to reduce this data.table, grouping by "TV.Show" where:
- I sum elements in corresponding numeric columns together, and
- use the first element of corresponding non-numeric columns such as "ID" and "Date" as the new value for the reduced data.table row.
Or in other words, I want to produce the following data.table:
# ID TV.Show Date Ratings.North Ratings.South
# x4 Doctor Who 2014-01-04 8.9 6.6
# x1 Farscape 2014-01-01 2.0 0.1
# x3 Star Trek 2014-01-03 4.8 1.8