1

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
John Smith
  • 1,077
  • 6
  • 21

1 Answers1

1

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 )]
akrun
  • 874,273
  • 37
  • 540
  • 662