简体   繁体   中英

How to subset multiple elements of a list R

I am trying to remove undesired values from elements in a list. The example below is a condensed version of my attempt at solving the problem. This system is going to be made into a shiny app so it needs to be reactive to any size or cardinality of input vectors (seen below as A:B, 'group...', remove) as these will be the indirect result of a user selection.

A <- c(35,35,2609,917,0)
B <- c(8,6,9,24,27,35)
C <- c(1,45,91,24)
D <- c(927,38,22,9)
E <- c(6361,7,43)

my.list <- list(A, B, C, D, E)

group1 <- c(1,2)
group2 <- c(3,5)

remove <- c(35, 24, 6361)

my.list[group1] <- my.list[group1] %>% subset(., !.%in% remove)

my.list

###final expected output

my.list

[[1]]
[1] 2609  917    0

[[2]]
[1]  8  6  9 27

[[3]]
[1]  1 45 91 24

[[4]]
[1] 927  38  22   9

[[5]]
[1] 6361    7   43

The solution should allow for any number of input groups that specify the location of the list elements to be subset, any number of elements to the list, and any number of values to be removed. (it shouldn't be reliant on any fixed cardinality of membership)

Thanks!

my.list[group1] %<>% lapply(function(x) setdiff(x, remove))

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