Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R: How to remove element from list by value or type

Tags:

loops

list

r

na

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!

like image 549
Merle Avatar asked Sep 06 '25 03:09

Merle


2 Answers

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.

like image 173
lebatsnok Avatar answered Sep 07 '25 22:09

lebatsnok


You can use which function to find the index of NA elements and then remove them by index:

example[-which(is.na(example))]
like image 42
Dandelion Avatar answered Sep 07 '25 23:09

Dandelion