Home > Enterprise >  Select list columns that match TRUE
Select list columns that match TRUE

Time:06-05

I have two lists as a result of some processing. The objective is to grab only those columns from the lists that is TRUE in the second list.

Here's some example data:

> first_try
[[1]]
      X1     X2     X3  X4
1 status income verbal sex

[[2]]
      X1     X2     X3     X4
1 status income verbal    sex
2 income verbal    sex status

> second_try
$`1`
     X1    X2    X3   X4
1 FALSE FALSE FALSE TRUE

$`2`
     X1    X2   X3   X4
2 FALSE FALSE TRUE TRUE

So for the first list we only select X4 from [[1]] because it has a value TRUE in second at [[1]], and from list [[2]] we only select X3,X4 because it has the value TRUE, and so forth.

I thought that I could somehow merge the two lists and try getting it that way, but I was having difficulties getting this to work.

something that I tried:

first <- list()
second <- list()
for(i in 1:length(second_try)){
  second[[i]]<-second_try[[i]] %>% pivot_longer(-c())
  first[[i]]<-first_try[[i]] %>% pivot_longer(-c()) 
}

first %>% mapply(function(x, y)inner_join(x, y, by='name'), second, .)

Expected output:

> first_try
[[1]]
 X4
sex

[[2]]
  X3       X4
verbal     sex
 sex      status

Reproducible code:

first_try<-list(structure(list(X1 = "status", X2 = "income", X3 = "verbal", 
    X4 = "sex"), row.names = 1L, class = "data.frame"), structure(list(
    X1 = c("status", "income"), X2 = c("income", "verbal"), X3 = c("verbal", 
    "sex"), X4 = c("sex", "status")), row.names = 1:2, class = "data.frame"))
second_try<-list(`1` = structure(list(X1 = FALSE, X2 = FALSE, X3 = FALSE, 
    X4 = TRUE), row.names = 1L, class = "data.frame"), `2` = structure(list(
    X1 = FALSE, X2 = FALSE, X3 = TRUE, X4 = TRUE), row.names = 2L, class = "data.frame"))

CodePudding user response:

You can do this with a single line of code in base R. Use Map to subset each member of first_try by the unlisted member at the equivalent position of second_try.

Map(function(a, b) a[unlist(b)], first_try, second_try)
#> [[1]]
#>    X4
#> 1 sex
#> 
#> [[2]]
#>       X3     X4
#> 1 verbal    sex
#> 2    sex status
  •  Tags:  
  • r
  • Related