4

I have a data.table that looks like this:

dt <- data.table(a = 1, b = 1, c = 1)

I need column b to be treated as an integer vector of variable length, so I can append additional elements to it. For instance, I want to add 2 to column b in the first row. I tried

dt[a == 1, b := c(b, 2)]

but that doesn't work. It gives me a warning:

Warning message:
In `[.data.table`(dt, a == 1, `:=`(b, c(b, 2))) :
  Supplied 2 items to be assigned to 1 items of column 'b' (1 unused)

What's the right syntax for this?

amonk
  • 1,769
  • 2
  • 18
  • 27
user3294195
  • 1,748
  • 1
  • 19
  • 36

1 Answers1

4
dt <- data.table(a = 1, b = 1:3, c = 1)
dt[, b := .(lapply(b, c, 2))][]
#   a   b c
#1: 1 1,2 1
#2: 1 2,2 1
#3: 1 3,2 1

If requiring a conversion to list first (i.e. when not already a list, and subsetting or doing a by), add dt[, b := .(as.list(b))] before the above.

eddi
  • 49,088
  • 6
  • 104
  • 155
  • This doesn't work for the given example i.e. I tried `dt <- data.table(a = 1, b = 1, c = 1); dt[, b := lapply(b, c, 2)][]`, and I get the same warning message as in my question. – user3294195 Jun 27 '17 at 15:13