Moe Sam
Moe Sam

Reputation: 63

Create multiple list columns dynamically in data.table at once

Is there a way to create multiple list columns at once in data.table?

Using code below i create two list columns, c1_list and c2_list, while grouping by x

DT = data.table(x  = c('a','a','b','b'),
            c1 = c(1,2,3,4),
            c2 = c(2,4,6,8))

DT[, .(c1_list = list(c1), c2_list = list(c2)), by = 'x']
#   x c1_list c2_list
#1: a     1,2     2,4
#2: b     3,4     6,8 

Instead, I was hoping for a dynamic shortcut somthing like

note: code below does not work - this is merely a suggestion of how it might look like

DT[, (c('c1_list', 'c2_list')) = lapply(mget(c('c1','c2')), list), by = 'x']

or

DT[, lapply(.SD, list), by = 'x', .SDcols = c('c1','c2')] %>%
    setnames(c('c1','c2'), c('c1_list','c2_list')

UPDATE: as RyanD pointed out the second solution works.

Upvotes: 1

Views: 75

Answers (1)

markus
markus

Reputation: 26343

You can do

DT[, lapply(.SD, list), by = x, .SDcols = paste0("c", 1:2)]
#   x  c1  c2
#1: a 1,2 2,4
#2: b 3,4 6,8

Upvotes: 1

Related Questions