[R] Faster process for creating a matrix based on matrix element comparison
Evgenia
evgts at aueb.gr
Fri Oct 28 20:40:12 CEST 2011
I have matrix data
data<-matrix(cbind(c(0,0,0),c(NA,0,1),c(1,1,1),c(0,1,1)),ncol=3)
and I want to create a new matrix by checking each element of the data and
put value 0 if i have NA and 1 otherwise.
For this reason i made the function below
pdata<-matrix(NA,ncol=ncol(data),nrow=nrow(data))
pdata<-sapply(1:nrow(data),function(i) sapply (1:ncol(data),function(j)
if (is.na(data[i,j])) {pdata[i,j]<-0} else {pdata[i,j]<-1}
))
pdata<-matrix(t(pdata),ncol=ncol(data),nrow=nrow(data))
with pdata
> pdata
[,1] [,2] [,3]
[1,] 1 1 1
[2,] 1 1 1
[3,] 1 1 1
[4,] 0 1 1
But in my case I have a matrix with 50000 rows and 10 colums
and the creation of pdata takes alot of time.
Could anyone have any suggestion to make pdata faster?
Thanks
--
View this message in context: http://r.789695.n4.nabble.com/Faster-process-for-creating-a-matrix-based-on-matrix-element-comparison-tp3948841p3948841.html
Sent from the R help mailing list archive at Nabble.com.
More information about the R-help
mailing list