0

I need to convert simple data.table to named vector.

Lets say I have data.table

a <- data.table(v1 = c('a', 'b', 'c'), v2 = c(1,2,3))

and I want to get the following named vector

b <- c(1, 2, 3)
names(b) <-  c('a', 'b', 'c')

Is there a way to do it simple

Ronak Shah
  • 377,200
  • 20
  • 156
  • 213
Lodyk Vovchak
  • 133
  • 2
  • 12

2 Answers2

3

Using setNames() in j:

a[, setNames(v2, v1)]
# a b c 
# 1 2 3 
s_baldur
  • 29,441
  • 4
  • 36
  • 69
0

We can use split and unlist to get it as named vector.

unlist(split(a$v2, a$v1))
#a b c 
#1 2 3
Ronak Shah
  • 377,200
  • 20
  • 156
  • 213