How to subset from a list in R

让人想犯罪 __ 提交于 2019-11-29 23:56:24

You could use sapply(mylist, "[", y):

mylist <- list(1:5, 6:10, 11:15)
sapply(mylist, "[", c(2,3))

Try using [ instead of [[ (and depending on what you're after you light actually want lapply).

From ?'[[':

The most important distinction between [, [[ and $ is that the [ can select more than one element whereas the other two select a single element.

Using 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)]})
DanO

purrr provides another solution for solving these kinds of list manipulations within the tidyverse

library(purrr)
library(dplyr)

desired_values <- c(1,3)

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

mylist

I don't think sgibb's answer gives what you would want. I suggest making a new function:

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

Then you can use it like this:

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

These both give

[[1]]
[1] "world"

[[2]]
[1] 3

which is what you would want, I think.

There are better ways of doing this, but here's a quick solution.

# 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
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!