CodeGuy
CodeGuy

Reputation: 28905

R - creating list from variable of names

Consider the following code

names = c("1","2","3")
values = c(1.0,1.5,0.5)
list(names = values)

This produces the following list

$names
[1] 1.0 1.5 0.5

But the list I desire is:

$`1`
[1] 1

$`2`
[1] 1.5

$`3`
[1] 0.5

In other words, list("1"=1.0,"2"=1.5,"3"=0.5)

So, how can I create such a list by starting with variables names and values as above?

Upvotes: 2

Views: 138

Answers (2)

Metrics
Metrics

Reputation: 15458

Map(function(x,y) y,names,values)

$`1`
[1] 1

$`2`
[1] 1.5

$`3`
[1] 0.5

Upvotes: 2

A5C1D2H2I1M1N2O1R2T1
A5C1D2H2I1M1N2O1R2T1

Reputation: 193677

You can use setNames and as.list:

setNames(as.list(values), names)
# $`1`
# [1] 1
#
# $`2`
# [1] 1.5
# 
# $`3`
# [1] 0.5

Upvotes: 4

Related Questions