[R] Faster process for creating a matrix based on matrix element comparison
Dennis Murphy
djmuser at gmail.com
Fri Oct 28 20:59:33 CEST 2011
> dat
[,1] [,2] [,3]
[1,] 0 0 1
[2,] 0 1 0
[3,] 0 1 1
[4,] NA 1 1
1 - is.na(dat)
[,1] [,2] [,3]
[1,] 1 1 1
[2,] 1 1 1
[3,] 1 1 1
[4,] 0 1 1
D.
On Fri, Oct 28, 2011 at 11:40 AM, Evgenia <evgts at aueb.gr> wrote:
> 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.
>
> ______________________________________________
> 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