I need to aggregate all my columns, but only if their values are 1, and group by an another columns.
Here is how I could perform this, step by step, i.e. column by column, from foo to out, the expected output.
set.seed(123)
foo <- data.table(id = rep(LETTERS[1:10], each = 10),
code = sample(c(111, 222, 333, 444), 100, replace = TRUE),
x1 = sample(0:1, 100, replace = TRUE),
x2 = sample(0:1, 100, replace = TRUE),
x3 = sample(0:1, 100, replace = TRUE),
x4 = sample(0:1, 100, replace = TRUE),
x5 = sample(0:1, 100, replace = TRUE),
x6 = sample(0:1, 100, replace = TRUE))
f1 <- foo[x1 == 1, .(x1 = uniqueN(code)), by = id]
f2 <- foo[x2 == 1, .(x2 = uniqueN(code)), by = id]
f3 <- foo[x3 == 1, .(x3 = uniqueN(code)), by = id]
setkey(f1, id)
setkey(f2, id)
setkey(f3, id)
out <- f1[f2,][f3,]
I'm sure there is an elegant and fast way to do this in data.table, maybe with a function and the .SDcols parameter, right?
But I can't find it...
Many thanks !!