John Smith - 1 year ago 59

R Question

Any more elegant way to do

`tdt`

`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 )]
```