简体   繁体   English

如何从列表列表中获取特定列表?

[英]How to get a specific list from a list of lists?

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". 如何提取名为“a”的所有元素的列表。 ie I would like to get list(1, 4, 7) asking for a . 即我想获得list(1, 4, 7)要求a

We can use pluck 我们可以使用pluck

library(tidyverse)
map(v, pluck, "a")
#[[1]]
#[1] 1

#[[2]]
# [1] 4

#[[3]]
# [1] 7

The corresponding method in base R would be base R的相应方法是

lapply(v, `[[`, "a")

In base R, we can use 在基地R,我们可以使用

unlist(v)[names(unlist(v))=="a"]

Or, if your prefer not to use unlist twice: 或者,如果您unlist两次使用unlist

(x <- unlist(v))[names(x)=="a"]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM