1

How do I use column in data table as variable name to fetch values from other columns based on the said column.

library(data.table)
a = c(2,3,5)
b = c(5,7,7)
c = c(1,2,3)
x = c ('a','b','c')
dt <- data.table(a,b,c,x)

> dt
   a b c x
1: 2 5 1 a
2: 3 7 2 b
3: 5 7 3 c

output I desire column y which is based on values of column x which contains the column names of values to be fetched.

dt
   a b c x y
1: 2 5 1 a 2
2: 3 7 2 b 7
3: 5 7 3 c 3

I tried

dt[,get(x)]

dt[,match(x,colnames(dt))]
Frank
  • 66,179
  • 8
  • 96
  • 180
aprilian
  • 621
  • 3
  • 17

1 Answers1

3

By looping through the sequence of rows, extract the value with get and assign it to create 'y'

dt[, y := .SD[, get(x), seq_len(.N)]$V1]
dt
#   a b c x y
#1: 2 5 1 a 2
#2: 3 7 2 b 7
#3: 5 7 3 c 3
akrun
  • 874,273
  • 37
  • 540
  • 662