[英]Bind a data.table and a vector
I have two data.tables: 我有两个data.tables:
require(data.table)
set.seed(11)
dt = data.table(a=c(1,2,3,2,1,3,2,3,2,1,2,3))
V = c(1/2,1/8,3/2)
names(V) = c('1','2','3')
I'd like to bind these two data.tables so that for each value in dt1$a corresponds (=stands on the same row) the value of V which name equals the value in dt1$a. 我想绑定这两个data.tables,以便dt1 $ a中的每个值都对应(=站在同一行上),V的值等于dt1 $ a中的值。 At the end, the newly constructed data.table should have ncol(dt1)+1 columns and nrow(dt1) rows.
最后,新构造的data.table应该具有ncol(dt1)+1列和nrow(dt1)行。 For example: As in row 6, a 3 appears in dt1$a, the value of V, named 3 should appears in row 6 of the newly created data.table.
例如:与第6行中的dt1 $ a中出现3一样,名为V的V值应出现在新创建的data.table的第6行中。
Hope this makes sense. 希望这是有道理的。 I expect this operation to be basic, it is just hard to me to explain it with simple words!
我希望这个操作是基本的,我很难用简单的话来解释它!
How about this? 这个怎么样?
dt[, V := V[as.character(a)]]
a V
1: 1 0.500
2: 2 0.125
3: 3 1.500
4: 2 0.125
5: 1 0.500
6: 3 1.500
7: 2 0.125
8: 3 1.500
9: 2 0.125
10: 1 0.500
11: 2 0.125
12: 3 1.500
Not the best way but it works: 不是最好的方法,但是它可以工作:
V <- data.table(V)
V <- V[,a:=unique(dt[,list(a)])]
merge(dt,V,by="a")
a V
1: 1 0.500
2: 1 0.500
3: 1 0.500
4: 2 0.125
5: 2 0.125
6: 2 0.125
7: 2 0.125
8: 2 0.125
9: 3 1.500
10: 3 1.500
11: 3 1.500
12: 3 1.500
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.