38

我有一个相当简单的任务,但没有找到一个好的解决方案。

> mylist  
[[1]]
 [1]  1  2  3  4  5  6  7  8  9 10

[[2]]
 [1] "a" "b" "c" "d" "e" "f" "g" "h" "i" "j" "k" "l" "m" "n" "o" "p" "q" "r" "s" "t" "u" "v" "w" "x" "y" "z"

[[3]]
[1] 25 26 27 28 29 30 31 32

y <- c(3,5,9)    

我想从mylist中提取列表中每个组件的子元素 3、5 和 9。我试过了,sapply[mylist,"[[",y]但运气不好!还有其他的,比如 vapply、lapply 等。在此先感谢您的帮助

毛里西奥·奥尔蒂斯

4

7 回答 7

38

你可以使用sapply(mylist, "[", y)

mylist <- list(1:5, 6:10, 11:15)
sapply(mylist, "[", c(2,3))
于 2012-03-08T20:21:49.483 回答
27

尝试使用[而不是[[(并且取决于您在点亮后实际想要的内容lapply)。

来自?'[['

[、[[ 和 $ 之间最重要的区别是 [ 可以选择多个元素,而其他两个选择单个元素。

于 2012-03-08T20:20:20.140 回答
11

使用lapply

# create mylist
list1<-1:10
list2<-letters[1:26]
list3<-25:32
mylist<-list(list1,list2,list3)

# select 3,5,9th element from each list
list.2 <- lapply(mylist, function(x) {x[c(3,5,9)]})
于 2015-11-23T11:47:50.707 回答
5

purrr为解决 tidyverse 中的此类列表操作提供了另一种解决方案

library(purrr)
library(dplyr)

desired_values <- c(1,3)

mylist <- list(1:5, letters[1:6], 11:15) %>% 
purrr::map(`[`,desired_values) 

mylist
于 2016-12-14T02:43:53.350 回答
3

一种对 list 的重复命名元素进行子集化的简单方法,类似于此处的其他答案。

所以下次我查这个问题时可以找到它

例如,"b"从重复列表中子集元素,其中每个元素都包含一个"a""b"子元素:

mylist <- list(
  list(
    "a" = runif(3),
    "b" = runif(1)
  ),
  list(
    "a" = runif(3),
    "b" = runif(1)
  )
)

mylist
#> [[1]]
#> [[1]]$a
#> [1] 0.7547490 0.6528348 0.2339767
#> 
#> [[1]]$b
#> [1] 0.8815888
#> 
#> 
#> [[2]]
#> [[2]]$a
#> [1] 0.51352909 0.09637425 0.99291650
#> 
#> [[2]]$b
#> [1] 0.8407162

blist <- lapply(
  X = mylist,
  FUN = function(x){x[["b"]]}
)

blist
#> [[1]]
#> [1] 0.8815888
#> 
#> [[2]]
#> [1] 0.8407162

reprex 包(v0.3.0)于 2019-11-06 创建

于 2019-11-06T03:18:05.527 回答
1

我认为 sgibb 的回答没有给出你想要的。我建议制作一个新功能:

subsetList <- function(myList, elementNames) {
    lapply(elementNames, FUN=function(x) myList[[x]])
}

然后你可以像这样使用它:

x <- list(a=3, b="hello", c=4.5, d="world")
subsetList(x, c("d", "a"))
subsetList(x, c(4, 1))

这些都给

[[1]]
[1] "world"

[[2]]
[1] 3

这就是你想要的,我想。

于 2018-04-03T10:57:16.703 回答
0

有更好的方法可以做到这一点,但这里有一个快速的解决方案。

# your values
list1<-1:10
list2<-letters[1:26]
list3<-25:32

# put 'em together in a list
mylist<-list(list1,list2,list3)

# function
foo<-function(x){x[c(3,5,9)]}

# apply function to each of the element in the list
foo(mylist[[1]])
foo(mylist[[2]])
foo(mylist[[3]])

# check the output

> foo(mylist[[1]])
[1] 3 5 9
> foo(mylist[[2]])
[1] "c" "e" "i"
> foo(mylist[[3]])
[1] 27 29 NA
于 2012-03-08T20:24:50.233 回答