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
  • 355,584
  • 18
  • 123
  • 178
Lodyk Vovchak
  • 133
  • 2
  • 12

2 Answers2

3

Using setNames() in j:

a[, setNames(v2, v1)]
# a b c 
# 1 2 3 
sindri_baldur
  • 25,109
  • 3
  • 30
  • 57
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
  • 355,584
  • 18
  • 123
  • 178