Update the vector in the data table.

I have it:

dt = data.table(index=c(1,2), items=list(c(1,2,3),c(4,5)))
#   index items
#1:     1 1,2,3
#2:     2   4,5

      

I want to change dt[index==2,items]

to c(6,7)

.

I tried:

dt[index==2, items] = c(6,7)
dt[index==2, items := c(6,7)]

      

+3


source to share


3 answers


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.

+5


source


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.

+2


source


This worked:

dt$items[[which(dt$index==2)]] = c(6,7)

      

0


source







All Articles