highbury
highbury

Reputation: 159

Extract values from data table

I have the following data table (in the example I just take 3 rows):

data <- data.table(var=c("a","b","c"), value=c(-1,2,1))    

I would like to extract each variable as value without subsetting each time that I need one of them. I would like to get the follwing output:

a <- -1
b <- 2
c <- 1

Upvotes: 1

Views: 963

Answers (3)

akrun
akrun

Reputation: 886938

An option is split to return a key/value pair. It is better not to create objects in the global environment

lst1 <- split(data$value, data$var)
lst1
#$a
#[1] -1

#$b
#[1] 2

#$c
#[1] 1

But, if we need it,

list2env(lst1, .GlobalEnv)
a
#[1] -1
b
#[1] 2
c
#[1] 1

Or another option is deframe and then use list2env

library(tibble)
list2env(as.list(deframe(data)), .GlobalEnv)

Upvotes: 2

NelsonGon
NelsonGon

Reputation: 13309

With purrr:

 res<-purrr::map2(data$var, data$value, 
            function(x,y) 
             x <- y

            )
names(res) <- data$var

The above sets the names after getting the result.

res

$a
[1] -1

$b
[1] 2

$c
[1] 1

With base's mapply, we could use:

  as.list(mapply(function(x,y) assign(x,y,new.env()),
       data$var,data$value))
$a
[1] -1

$b
[1] 2

$c
[1] 1

Or:

 mapply(function(x,y) append(list(),y),
       data$var,data$value)
$a
[1] -1

$b
[1] 2

$c
[1] 1

Upvotes: 1

Sotos
Sotos

Reputation: 51582

Though creating objects in the global environment is not recommended, we can try eval(parse(...)) methodology to address your question,

eval(parse(text = do.call(paste, c(data, sep = '<-'))))
a
#[1] -1
b
#[1] 2
c
#[1] 1

Upvotes: 1

Related Questions