Reputation: 105
I have a list containing lists and NAs. I'd like to filter the NAs out, but I don't know the exact name or position of the NAs.
I googled a lot, but only found how to remove elements by name or by indexing, but this is not what I'm looking for.
Here's an example of how my list looks like:
example <- list(list(1,2,3), list(2,3,4), NA, list(2,3,4))
My output looks like this:
Name Type Value
example list[[4]] List of length 4
[[1]] list[[3]] List of length 3
[[2]] list[[3]] List of length 3
[[3]] logical NA <-I'd like to remove this row
[[4]] list[[3]] List of length 3
I'd like to write a loop that removes an element from my list if the value is "NA" or the type is "logical". Thanks in advance for your help!
Upvotes: 4
Views: 9814
Reputation: 421
This one is a simple method to remove NA values from R list
example <- example[!is.na(example)]
Upvotes: 3
Reputation: 6459
It depends on your data structure. With your example, the following will work:
example[!is.na(example) & !is.logical(example)]
It becomes more complicated if the sub-lists can contain NA
's that you want to remove as well.
Upvotes: 4
Reputation: 756
You can use which
function to find the index of NA
elements and then remove them by index:
example[-which(is.na(example))]
Upvotes: 3