[英]Vector as entry in `data.table`
I have a data.table
that looks like this: 我有一个数据
data.table
,看起来像这样:
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. 我需要将
b
列视为可变长度的整数向量,因此可以向其附加其他元素。 For instance, I want to add 2
to column b
in the first row. 例如,我想在第一行的
b
列中添加2
。 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? 正确的语法是什么?
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 (ie when not already a list
, and subsetting or doing a by
), add dt[, b := .(as.list(b))]
before the above. 如果需要先转换为
list
(例如,当还没有list
并设置子集或执行by
),则在上面添加dt[, b := .(as.list(b))]
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.