John Smith John Smith - 1 year ago 53
R Question

converting two column data table to data table with colnames from one column and values from the other

Any more elegant way to do

tdt
as shown in the following example using base or data.table functions and operations only?

library(data.table)
dt <- data.table(a = letters[1:5], b = 1:5)
dt
# a b
# 1: a 1
# 2: b 2
# 3: c 3
# 4: d 4
# 5: e 5
tdt <- data.table(t(matrix(dt$b, dimnames = list(dt$a, NULL))))
tdt
# a b c d e
# 1: 1 2 3 4 5

Answer Source

We can use dcast

dcast(dt[, rn := 1], rn~a, value.var = "b")[, rn := NULL][]
#   a b c d e
#1: 1 2 3 4 5

Or

setDT(setNames(as.list(dt$b), dt$a))[]
#   a b c d e
#1: 1 2 3 4 5

Or

dt[, setNames(as.list(b),a )]