[R] Replace missing values in lapply

From: Doran, Harold <HDoran_at_air.org>
Date: Wed 24 Jan 2007 - 15:40:11 GMT


I have some matrices stored as elements in a list that I am working with. On example is provided below as TP[[18]]

> TP[[18]]

      level2
level1 1 2 3 4

     1 79  0  0  0
     2  0  0  0  0
     3  0  0  0  0
     4  0  0  0  0

Now, using prop.table on this gives

> prop.table(TP[[18]],1)

      level2
level1 1 2 3 4

     1   1   0   0   0
     2                
     3                
     4      

It is important for the zero's to retain their position as this matrix will subsequently be used in some matrix multiplication and hence, must be of dimension 4 by 4 so that is it conformable for multiplcation with another matrix.  

In looking at the structure of the object resulting from prop.table I see NaNs, and so I can do this

> rr <- TP[[18]]
> rr[is.na(rr)] <- 0
> rr

      level2
level1 1 2 3 4

     1 79  0  0  0
     2  0  0  0  0
     3  0  0  0  0
     4  0  0  0  0

This is exactly what I want for each matrix. But, I have multiple matrices stored within the list that need to be changed and so I am trying to resolve this via lapply, but something is awry (namely the user), but I could use a little help.

I was thinking the following function should work, but it doesn't. It reduces each matrix within the list to a 0.

PP <- lapply(TP, function(x) x[is.na(x)] <- 0)

Am I missing something obvious?

Harold

        [[alternative HTML version deleted]]



R-help@stat.math.ethz.ch mailing list
https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide http://www.R-project.org/posting-guide.html and provide commented, minimal, self-contained, reproducible code. Received on Thu Jan 25 15:55:01 2007

Archive maintained by Robert King, hosted by the discipline of statistics at the University of Newcastle, Australia.
Archive generated by hypermail 2.1.8, at Thu 25 Jan 2007 - 05:30:29 GMT.

Mailing list information is available at https://stat.ethz.ch/mailman/listinfo/r-help. Please read the posting guide before posting to the list.