statwoman
statwoman

Reputation: 398

Omitting the whole list if NA present

Assume I have a list of lists as:

d <- list(matrix(c(1:6),nrow=3,ncol=2),matrix(c(7:12),nrow=3,ncol=2))
e <- list(matrix(c(1:6),nrow=3,ncol=2),matrix(c(7:9,NA,NA,12),nrow=3,ncol=2))
f <- list(d,e)
rapply(f, na.omit, how = "replace")

when I use this rapply function, it just removes the rows that have NA in them. I want the whole list removed, if any NA is found there. What I mean is that since we have NA in list e, then I want list e completely gone from list f. How can I do this?

PS. The real data that I am working with is slightly different than what I replicated here. It is a long list of over 550 lists, which each are 8 x 6 dataframes. Here is a snapshot of how it looks like. I'm not sure if the answer to what I replicated here would be the same for my real data but let's give it a try! (In the real data, some of Bid Yield values are NA's)

PS2. I can share the data via google drive, if you think the answer is different.

enter image description here

Any helps would be appreciate!

Upvotes: 1

Views: 57

Answers (2)

Tim Biegeleisen
Tim Biegeleisen

Reputation: 520978

Here is a base R approach using the apply functions:

ind <- sapply(f, function(x) sum(sapply(x, function(y) sum(is.na(y)))) == 0)
f[ind]

[[1]]
[[1]][[1]]
     [,1] [,2]
[1,]    1    4
[2,]    2    5
[3,]    3    6

[[1]][[2]]
     [,1] [,2]
[1,]    7   10
[2,]    8   11
[3,]    9   12

Note that the e list of matrices is completely removed, as one of that list's matrices has an NA value in it.

Data:

d <- list(matrix(c(1:6),nrow=3,ncol=2), matrix(c(7:12), nrow=3, ncol=2))
e <- list(matrix(c(1:6),nrow=3,ncol=2), matrix(c(7:9,NA,NA,12), nrow=3, ncol=2))
f <- list(d, e)

Upvotes: 1

Ronak Shah
Ronak Shah

Reputation: 388862

You can use Filter :

Filter(function(x) all(!is.na(unlist(x))), f)

[[1]]
#[[1]][[1]]
#     [,1] [,2]
#[1,]    1    4
#[2,]    2    5
#[3,]    3    6

#[[1]][[2]]
#     [,1] [,2]
#[1,]    7   10
#[2,]    8   11
#[3,]    9   12

Upvotes: 2

Related Questions