首页 > 解决方案 > 如何将列表转换为其中一个字段的值向量?

问题描述

l = list()
l[[1]] = list(); l[[1]]$asdf = 'jkl'; l[[1]]$qwerty = 5
l[[2]] = list(); l[[2]]$asdf = 'zxcv'; l[[2]]$qwerty = 55
l[[3]] = list(); l[[3]]$asdf = 'poiu'; l[[3]]$qwerty = 555

现在我想以某种方式qwerty从这个列表中提取 s ;即我想获得一个等价的,c(5, 55, 555)因为qwerty这个列表的连续元素的字段的值是5, 55, 555

如何获得这个?

(如果我陷入 XY:我真正想要实现的是获取该列表中其qwerty字段具有最大价值的元素;我认为获得它的一种方法是将 s 提取到我可以调用qwerty的中间值上)numericmax

标签: rlistfield

解决方案


我们可以pluck通过循环遍历“qwerty”list元素map

library(tidyverse)
map_dbl(l, pluck, "qwerty")
#[1]   5  55 555

或使用sapplyfrombase R

sapply(l, `[[`, "qwerty")
#[1]   5  55 555

max行以获得最大值

max(sapply(l, `[[`, "qwerty"))
#[1] 555

如果它是元素list

i1 <- which.max(sapply(l, `[[`, "qwerty"))
l[i1]
#[[1]]
#[[1]]$asdf
#[1] "poiu"

#[[1]]$qwerty
#[1] 555

或者另一种选择是

l %>%
    transpose %>%
    .$qwerty %>% 
    unlist %>% 
    which.max %>% 
    magrittr::extract(l, .)

推荐阅读