Error when trying to store list in data.table of length 1

和自甴很熟 提交于 2021-02-11 08:13:40

问题


When trying to store a vector in a data.table, this works only when the data.table has length of more than one.

Please find below a simplified version of the problem

library(data.table)

Working fine

dt <- data.table( a = c("a", "b"), l = list())
dt$l[[1]] <- c(1:3) 

Results in:

   a     l
1: a 1,2,3
2: b

Producing Error

dt <- data.table( a = c("a"), l = list())
dt$l[[1]] <- c(1:3) 

Error in [<-.data.table(x, j = name, value = value) : Supplied 3 items to be assigned to 1 items of column 'l'. The RHS length must either be 1 (single values are ok) or match the LHS length exactly. If you wish to 'recycle' the RHS please use rep() explicitly to make this intent clear to readers of your code.

Expected result in:

   a     l
1: a 1,2,3

回答1:


Is this what you're looking for?

dt <- data.table(a = "a", l = list())
dt[1L, l := list(list((1:3)))]

Results in:

   a     l
1: a 1,2,3



来源:https://stackoverflow.com/questions/57290514/error-when-trying-to-store-list-in-data-table-of-length-1

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!