0
votes

I'm looking for a way to replace NAs in various list items using the purrr::map() suite of functions in R. It seems like it should be an easy task but I can't get it to work.

The following works:

 vec1 <- c(3,6,7,NaN)
 vec1[is.na(vec1)] <- 0

But when I try to do this for a list of vectors using map() it doesn't work:

 library(purrr)

 vec1 <- c(3,6,7,NaN)
 vec2 <- c(2,3,4)
 vec3 <- c(1,6,NaN,NaN,1)

 veclist <- list(a = vec1,
                 b = vec2,
                 c = vec3)

 veclistnew <- map(veclist, function(vec){vec[is.na(vec)] <- 0})

Thoughts? I would like the output to be a list of the original vectors with the NAs replaced by 0s.

3

3 Answers

3
votes

You can do the following:

na_to_y <- function(x, y){
  x[is.na(x)] <- y
  x # you need to return the vector after replacement
}

map(veclist, na_to_y, 0)
3
votes

Another option is replace

library(purrr)
veclist %>% 
    map(~replace(., is.nan(.), 0))
#$a
#[1] 3 6 7 0

#$b
#[1] 2 3 4

#$c
#[1] 1 6 0 0 1
2
votes

You could also use coalesce from dplyr:

library(dplyr)
veclistnew <- map(veclist, ~coalesce(., 0))

> veclistnew
$a
[1] 3 6 7 0

$b
[1] 2 3 4

$c
[1] 1 6 0 0 1