This is such a basic question and for some reason I can't figure out how to get this right. Suppose I have a list of lists
v <- list(
list(a=1, b=2, c=3),
list(a=4, b=5, c=6),
list(a=7, b=8, c=9))
How do I pull out a list of all elements that are named "a". ie I would like to get list(1, 4, 7)
asking for a
.
We can use pluck
library(tidyverse)
map(v, pluck, "a")
#[[1]]
#[1] 1
#[[2]]
# [1] 4
#[[3]]
# [1] 7
The corresponding method in base R
would be
lapply(v, `[[`, "a")
In base R, we can use
unlist(v)[names(unlist(v))=="a"]
Or, if your prefer not to use unlist
twice:
(x <- unlist(v))[names(x)=="a"]
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.