Update the vector in the data table.
One way to solve the problem is to use ifelse
:
dt[,items:=ifelse(index==2,list(c(6,7)),items)]
index items
1: 1 1,2,3
2: 2 6,7
EDIT correct answer:
dt[index==2,items := list(list(c(6,7)))]
Indeed, you will need another list, because data.table uses list(.)
to look up values ββto assign to columns by reference.
There are two ways to use the operator :=
in data.table
:
-
LHS form: = RHS:
DT[, c("col1", "col2", ..) := list(val1, val2, ...)]
The RHS requires an argument
list()
. To add a list column you need to wrap another list (as shown above). -
Functional form:
DT[, `:=`(col1 = val1, ## some comments col2 = val2, ## some more comments ...)]
It is especially helpful to add some comments along with the assignment.
source to share
dt[index==2]$items[[1]] <- list(c(6,7))
dt
# index items
# 1: 1 1,2,3
# 2: 2 6,7
The problem is, how you set it up dt$items
is a list, not a vector, so you need to use list indexing (for example dt$items[[1]]
). But AFAIK you cannot update a list item by reference, so for example
dt[index==2,items[[1]]:=list(c(6,7))]
will not work.
BTW, I also see no point in using data.tables for this.
source to share