Kaleb
Kaleb

Reputation: 1022

Unpacking a vector into a list with each element of vector as separate elements in list

With the following code, I am creating a list:

scales <- c(p="hye", r="t3")
details <- list(t=20,y="c", scales)

At the moment the above gives me a list as so:

$t
[1] 20

$y  
[1] "c"

[[3]]
p     r 
"hye"  "t3"

However I want a list like so:

$t
[1] 20

$y  
[1] "c"

$p      
[1] "hye"  

$r
[1] "t3"

Since this is going to be reused in a function I want to keep scales as a vector argument that I can then insert into a list. How can I do this?

Upvotes: 2

Views: 555

Answers (2)

Tim P
Tim P

Reputation: 1383

The solution is:

details = c(list(t=20,y="c"),scales)

Upvotes: 5

Gavin Simpson
Gavin Simpson

Reputation: 174788

You want to concatenate vis c() two lists, so use as.list() to convert the scales vector into a list before forming details:

> details <- c(list(t=20, y="c"), as.list(scales))
> details
$t
[1] 20

$y
[1] "c"

$p
[1] "hye"

$r
[1] "t3"

Upvotes: 3

Related Questions