2

In below example, I need to assign a list to a data.table's variable code, so that value list(11,22) is assigned to dt$code. How do I do that?

dt <- data.table(1:3)
dt$code <- list()
dt[V1==2, code:=list(11,22)] # does not work
dt[V1==2, code:=.(list(11,22))] # does not work

My question is simpler and shorter than in the earlier post. Thanks for the answer:

dt[V1==2, code:=list(list((list(11,22)))]   # works !
3

1 Answer 1

0
dt[V1==2, code:=list(list(list(11,22)))]  # works !

This can also be written as

dt[V1==2, code:=.(.(.(11,22)))]  

which is actually synonymous to

dt[V1==2, code:=.(.(c(11,22)))]  

Note however that in this case, it is a vector, rather than list, that is assigned to variable code for V1==2.

Note also that it is not possible (as of yet) to do either of these:

dt[all(code==c(11,22))] 
dt[, ifelse(all(code==c(11,22)), T, F)] 

which negates quite abit the value of using vectors as variable types for data.table.

PS. Added - as per Matt's comment below

The new development release of data.table will make this question obsolete. Starting from 1.12.3 release, it will be possible to write either way including dt[V1==2, code:=list(11,22)].

Sign up to request clarification or add additional context in comments.

4 Comments

This has been improved in dev 1.12.3 recently. See news item 4 : github.com/Rdatatable/data.table/blob/master/NEWS.md
@Matt, Do you plan to add functionality to compare list variables so that we can do this: dt[code==list(list(list(11,22)))] ? (this would really boost the use of lists within data.table)
Thanks @Matt. 1.12.3 will make this question obsolete. Pasted from link above: > DT[2, B:=letters[9:13]] # was error, now works > DT[2, B:=.(letters[9:13])] # was error, now works > DT[2, B:=.(list(letters[9:13]))] # .(list()) was needed, still works. Would it however be possible to do this: DT[B==letters[9:13]] ?
DT[B==letters[9:13]] is technically possible as a vector scan but are you really sure that a multi-column key (or index) is not more appropriate; e.g. setkey(DT, id1, id2, id3, id4, id5); DT[as.list(letters[9:13)]] ?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.