Home > OS >  How to filter in lapply list with conditionals lapply, Filter, Between in R?
How to filter in lapply list with conditionals lapply, Filter, Between in R?

Time:05-23

I have this:

res.list<-list(c("X2", "X3", "X4"), c("X2", "X3", "X4"), c("X1", "X2", "X3"))

result<- lapply(res.list, function(x) {
      unlist(lapply(seq_along(x), function(y) combn(x, y, list)), recursive = FALSE)
    })
result<-lapply(result, Filter,f = function(x){
    ifelse(
    seq_along(result)==1, 
    between(length(x),1,3),
    between(length(x),2,2)
    ) %>%.[!is.na(.)]})

1- I have a list "res.list"

2- Combines columns 1 to "n" without repetition.

3- Filter results by condition and delet element is NULL

Expected output: "result"

[[1]]
[[1]][[1]][1] "X2"
[[1]][[2]][1] "X3"
[[1]][[3]][1] "X4"
[[1]][[4]][1] "X2" "X3"
[[1]][[5]][1] "X2" "X4"
[[1]][[6]][1] "X3" "X4"
[[1]][[7]][1] "X2" "X3" "X4"

[[2]]
[[2]][[4]][1] "X2" "X3"
[[2]][[5]][1] "X2" "X4"
[[2]][[6]][1] "X3" "X4"

[[3]]
[[3]][[4]][1] "X2" "X3"
[[3]][[5]][1] "X2" "X4"
[[3]][[6]][1] "X3" "X4"

the code does not return the result Expected output, if you have any idea to improve and make it more generic it will be enlightening.

Best regards

CodePudding user response:

We may need

result[-1] <- lapply(result[-1], \(x) x[between(lengths(x), 1, 2)])
  • Related