简体   繁体   中英

R remove element from list

How do I remove an element from a list in R? Imagine this workflow:

# create list
my_list <- lapply(1:10, function(x) x)
# find which ones to exclude
my_list_boolean <- sapply(my_list, function(x) ifelse(x%%2>0,F,T))
# does not work like this!
my_list[[my_list_boolean]]

Is there a solution not having to use a for loop and create a big logic around my statement?

Do you mean this?

my_list[my_list_boolean]
#[[1]]
#[1] 2
#
#[[2]]
#[1] 4
#
#[[3]]
#[1] 6
#
#[[4]]
#[1] 8
#
#[[5]]
#[1] 10

Just use [] and not [[]]

my_list <- lapply(1:10, function(x) x)
# find which ones to exclude
my_list_boolean <- sapply(my_list, function(x) ifelse(x%%2>0,F,T))
# does not work like this!
my_list[my_list_boolean]
#> [[1]]
#> [1] 2
#> 
#> [[2]]
#> [1] 4
#> 
#> [[3]]
#> [1] 6
#> 
#> [[4]]
#> [1] 8
#> 
#> [[5]]
#> [1] 10

Created on 2018-11-03 by the reprex package (v0.2.1)

You can thus select element of the list with logical vector and not the content (which is [[]]

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.

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