How to omit NA from a nested list?

I work with a list of lists - let's call it L - in R, where the sub sheets are the same length and complemented by NA. Ideally, I would like to remove only NA elements from each sublist, and one of the solutions I came up with is L <- lapply(L, na.omit) . It seems to almost work; however, for each sub-list, the behavior is such that, for example,

 [[1]] [1] "0" "12345" "12346" "12347" "12348" "12349" "12340" "12341" "12342" NA NA NA NA NA NA [16] NA NA NA NA NA NA NA NA NA NA NA 

becomes

 [[1]] [1] "0" "12345" "12346" "12347" "12348" "12349" "12340" "12341" "12342" attr(,"na.action") [1] 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 attr(,"class") [1] "omit" 

I'm a little confused, to be honest, what about the extra attr() and such on my list? Is there a solution that will not add them to the list? I tried na.exclude , but it gives the same result. Is there something I'm missing? Thanks in advance:)

+4
source share
2 answers

No reason to be confused ... in the "Details" section ?na.omit says:

If na.omit deletes cases, the line numbers from them form the Na.action attribute of the result, omit class.

Try a subset of each list item with is.na :

 L <- lapply(L, function(x) x[!is.na(x)]) 
+8
source

Another solution using higher order functions

 lapply(L, Filter, f = Negate(is.na)) 
+3
source

All Articles