jpsmith
jpsmith

Reputation: 17185

Removing NA from list of lists in R

I have a function that takes a nested list (or list of lists) of integers as the input and assigns values of NA randomly according to some probability, p1. I would like to extend this function to remove the NAs from the list.

I know removing NAs is a common question on the internet and have reviewed the the questions on Stack Overflow and elsewhere, but none of the solutions work. In general, the questions posed do not refer to an actual list of lists.

I have tried:

#Example data
L.miss <- list(list(1, 3, c(0, NA, 0), c(0, 0)),
            list(1, 6, c(0, 3, NA, 0, NA, 0), c(0, NA, 0, 1, 0, 0), 1, NA, c(0, 0)),
            list(1, 0))

# attempts 
test1 <- lapply(L.miss, function(x) x[!is.na(x)]) # Doesn't replace NAs
test2 <- lapply(L.miss, Filter, f = Negate(is.na)) # Turns nested lists to NULL
test3 <- lapply(L.miss, na.omit) # Doesn't replace NAs

# desired output:
L.want <- list(list(1, 3, c(0, 0), c(0, 0)), 
              list(1, 6, c(0, 3, 0, 0), c(0, 0, 1, 0, 0), 1, logical(0), c(0, 0)), 
              list(1, 0))

Upvotes: 4

Views: 1557

Answers (3)

LMc
LMc

Reputation: 18622

You could also do this using purrr:

library(purrr)
modify_tree(L.miss, leaf = na.omit)

Or using only purrr functions:

modify_tree(L.miss, leaf = ~ discard(.x, is.na))

Upvotes: 1

jpsmith
jpsmith

Reputation: 17185

As an alternative to na.omit in the rapply function, which produces some extraneous information, I also found the following code to perform better for my purposes:

rapply(test2,function(x) x[!is.na(x)], how="replace")

Upvotes: 0

G. Grothendieck
G. Grothendieck

Reputation: 269481

Use rapply:

rapply(L.miss, na.omit, how = "replace")

Upvotes: 9

Related Questions