0
votes

I have two 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. At the end, the newly constructed data.table should have ncol(dt1)+1 columns and nrow(dt1) rows. 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.

Hope this makes sense. I expect this operation to be basic, it is just hard to me to explain it with simple words!

2
it's just hard to explain with simple words - that's why showing the output would help A LOT!Arun

2 Answers

3
votes

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
0
votes

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