[R] how to replace NA values in a list

Roland Rau roland.rproject at gmail.com
Fri Aug 1 20:54:23 CEST 2008


Hi,

to be honest, I never created a matrix of lists before, but hopefully 
this code will help you?

set.seed(12345)
my.pool <- c(NA, 0:10)
n <- 25

alist <- list(sample(x=my.pool, size=n, replace=TRUE))
alist

mymatrix <- matrix(rep(alist, 6*3), nrow=6)
mymatrix2 <- lapply(X=mymatrix, FUN=function(x) ifelse(is.na(x),0,x))
mymatrix2


Best,
Roland

Shang Liu wrote:
> I have a matrix named "spec" (see below), it is a 6x3 matrix, and each element of spec is a list. For example, spec[1,"wavenumber"] is a list, and it contains 1876 numeric numbers and NAs. I want to replace the NAs to zero, but don't know how to change it, the difficulty may be all the elements are of the class list, so it is hard to change. 
> 
> Thank you for your help! 
> 
> matrix spec:
> 
>      wavenumber   prescan      postscan    
> H001 Numeric,1876 Numeric,1876 Numeric,1876
> H002 Numeric,1876 Numeric,1876 Numeric,1876
> H003 Numeric,1876 Numeric,1876 Numeric,1876
> H004 Numeric,1876 Numeric,1876 Numeric,1876
> H005 Numeric,1876 Numeric,1876 Numeric,1876
> H006 Numeric,1876 Numeric,1876 Numeric,1876
> 	[[alternative HTML version deleted]]
> 
> ______________________________________________
> R-help at r-project.org 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.
>



More information about the R-help mailing list