Reputation: 23
I'm trying to extract a single element from a list in R and store the element with its vector name as a new list.
Let's assume that I have a list called mylist that has an arbitrary amount of named vectors within and the length of each vector can vary, e.g.
mylist <- list("var1" = c(1,2,3), "var2" = c(10,8,4,2), "var3" = c(6,3), ...)
I know I can get an individual element by using either the name or the index of the vector, e.g.
mylist[["var1"]][1]
[1] 1
mylist[[2]][3]
[1] 4
However, these are only the values. What I want is to create a new list from this extracted value and use the original name of the vector where it was extracted from, something like
element1
$var1
[1] 1
element2
$var2
[1] 4
where element1 and element2 are the new lists. Is there an efficient way of doing this?
Upvotes: 2
Views: 2501
Reputation: 1855
You can use combination of pluck
and list
as shown below.
library(purrr)
mylist <- list("var1" = c(1,2,3), "var2" = c(10,8,4,2), "var3" = c(6,3))
element1 <- mylist %>% pluck("var1") %>% .[1] %>% list("var1" = .)
element2 <- mylist %>% pluck("var2") %>% .[3] %>% list("var2" = .)
Upvotes: 1
Reputation: 886998
We can use map2
from purrr
library(purrr)
map2(mylist, c(1, 3), `[[`)
-output
#$var1
#[1] 1
#$var2
#[1] 4
or using pluck
map2(mylist, c(1, 3), pluck)
Or with Map
from base R
Map(`[[`, mylist, c(1, 3))
-output
#$var1
#[1] 1
#$var2
#[1] 4
mylist <- list("var1" = c(1,2,3), "var2" = c(10,8,4,2))
Upvotes: 0
Reputation: 39595
Try this. You can use mapply()
defining a function with two elements: a list x
and a vector n
which contains the desired positions of elements to extract. With that you can wrap the function using indexing in order to obtain a list L
close to what you expect. Here the code:
#Data
mylist <- list("var1" = c(1,2,3), "var2" = c(10,8,4,2))
#List
L <- mapply(function(x,n) x[n],x=mylist,n=c(1,3),SIMPLIFY = F)
Output:
L
$var1
[1] 1
$var2
[1] 4
Upvotes: 0