Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace NaN values in a list with zero (0)

Tags:

r

nan

Hi dear I have a problem with NaN. I am working with a large dataset with many variables and they have NaN. The data is like this:

z=list(a=c(1,2,3,NaN,5,8,0,NaN),b=c(NaN,2,3,NaN,5,8,NaN,NaN))

I used this commands to force the list to data frame but I got this:

z=as.data.frame(z)
> is.list(z)
[1] TRUE

> is.data.frame(z)
[1] TRUE
> replace(z,is.nan(z),0) 
Error en is.nan(z) : default method not implemented for type 'list'

I forced z to data frame but it wasn't enough, maybe there is a form to change NaN in list. Thanks for your help. This data is only an example my original data has 36000 observations and 40 variables.

like image 765
Duck Avatar asked Mar 23 '13 00:03

Duck


1 Answers

This is a perfect use case for rapply.

> rapply( z, f=function(x) ifelse(is.nan(x),0,x), how="replace" )
$a
[1] 1 2 3 0 5 8 0 0

$b
[1] 0 2 3 0 5 8 0 0

lapply would work too, but rapply deals properly with nested lists in this situation.

like image 127
Ari B. Friedman Avatar answered Oct 17 '22 19:10

Ari B. Friedman