[英]How to cross-referencing columns in data.table
I need to cross-reference from a column in a data.table to multiple other columns in it. 我需要从data.table中的一列交叉引用到其中的多个其他列。 As an example I have : 例如,我有:
library(data.table)
dt = data.table(mtcars)
sub = dt[1:3]
sub[, v1 := ('vs', 'am', 'gear')]
head(dt)
mpg cyl disp hp drat wt qsec vs am gear carb
21.0 6 160 110 3.90 2.620 16.46 0 1 4 4
21.0 6 160 110 3.90 2.875 17.02 0 1 4 4
22.8 4 108 93 3.85 2.320 18.61 1 1 4 1
So the column v1 contains the information which column the value for should be taken. 因此,列v1包含应采用该值的列的信息。 So for the sub i want a new column with value : row 1: the value from the column 'vs' from the first row row 2: the value from column 'am' from the second row row 3: the value from the third row of 'gear' in short an a data.table like 因此,对于子项目,我想要一个新的值列:第1行:第1行第'vs'列的值第2行:第2行第3行的'am'列的值:第3行第3行的值简而言之,“齿轮”的数据表
mpg cyl disp hp drat wt qsec vs am gear carb v1 v2
21.0 6 160 110 3.90 2.620 16.46 0 1 4 4 vs 0
21.0 6 160 110 3.90 2.875 17.02 0 1 4 4 am 1
22.8 4 108 93 3.85 2.320 18.61 1 1 4 1 gear 4
unfortunately somthing like 不幸的是,像
sub[, v2 := get(value))]
or 要么
sub[, v2 := get((sub$value))]
doesn't lead to the solution as v2 would be equal to [0,0,1]
but not [0,1,4]
Thanks in advance 不会导致解决方案,因为v2等于[0,0,1]
但不等于[0,1,4]
Okay, this was easier than I thought, but for anyone who wants to achieve something similar a group by for the respective column solved my problem. 好的,这比我想象的要容易,但是对于任何想要通过各自专栏达成类似目标的人来说,都可以解决我的问题。 SO the solution would be : 所以解决方案将是:
sub[, v2 := get(c(value)), by = value]
Which leads to the desired result : 这导致了预期的结果:
head(sub[, .(mpg, v1, v2 )]
mpg v1 v2
21.0 vs 0
21.0 am 1
22.8 gear 4
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.