user1916067
user1916067

Reputation: 137

Subsetting a list based on a conditions of sublists in R?

I am hoping to get some pointers on how to implement this with the apply family of functions. I have a list (listbin)and want to subset using contents in the sublist (x and Ineligible) of my list.

The structure of the list is shown below:

[[1]]
[[1]]$x
[1] "2015-01-12"

[[1]]$rslts
factor(0)
Levels: PD

[[1]]$Ineligible
[1] 0

[[2]]$x
[[1]]$rslts
factor(0)
Levels: 0 1 A CR D E IS PD PR SD

[[1]]$Ineligible
[1] 0

...

For my purposes, this code works perfectly for 1, 2 and 3 of my sublists, but I am looking for an elegant way to do this throughout my sublists.

'[['(listbin, 1)$x [which( '[['(listbin, 1)$Ineligible==0 ) ]
'[['(listbin, 2)$x [which( '[['(listbin, 2)$Ineligible==0 ) ]
'[['(listbin, 3)$x [which( '[['(listbin, 3)$Ineligible==0 ) ]

Upvotes: 1

Views: 120

Answers (1)

akrun
akrun

Reputation: 886938

We could create a function and then loop over the index and extract the components

f1 <- function(lst1, i, nm1, nm2){
    '[['(lst1, i)[[nm1]] [which( '[['(lst1, i)[[nm2]]==0 ) ]  
   }

lapply(1:3, function(i) f1(listbin, i = i, 'x', 'Ineligible'))

Upvotes: 1

Related Questions