I have a list object in R with NaN/Inf/NA values:
dat <- list(a=matrix(c(2,0/0,10/0,NA),nrow=2), b=matrix(c(-3,0,NA,1),nrow=2))
How can I replace the NaN/Inf/NA elements to 0?
We can replace
the non finite values to 0 by looping over the list
elements with lapply
lapply(dat, function(x) replace(x, !is.finite(x), 0))
# [,1] [,2]
#[1,] 2 0
#[2,] 0 0
#$b
# [,1] [,2]
#[1,] -3 0
#[2,] 0 1
You could also do this by checking if x%%1==0
:
ls <- unlist(dat)
ls[is.na(ls%%1==0)] <- 0
relist(ls, skeleton = dat)
# $a
# [,1] [,2]
# [1,] 2 0
# [2,] 0 0
# $b
# [,1] [,2]
# [1,] -3 0
# [2,] 0 1
Or one-line code as @akrun's answer:
lapply(dat, function(x) replace(x, is.na(x%%1==0), 0))