Julian TszKin Chan
2011-Jul-20 15:16 UTC
[R] transforming a matrix of logical to 0 and 1 while keeping the dim of matrix
Hi all, Suppose I have a matrix of logical value: x<-matrix(c(TRUE,FALSE,TRUE,FALSE,TRUE,FALSE,TRUE,FALSE,TRUE),nrow=3) I would like to change the value of FALSE to 0 and TRUE to 1. An obvious way to do it is : y<-as.numeric(x) However this method doesn't keep the dim of x. I also need to copy the dim information to y too. attributes(y)<-attributes(x) Is this a correct way to do it in R? Is there any single step function which can do the something? Thanks Regards, TszKin Julian
Sarah Goslee
2011-Jul-20 15:27 UTC
[R] transforming a matrix of logical to 0 and 1 while keeping the dim of matrix
How about this:> x<-matrix(c(TRUE,FALSE,TRUE,FALSE,TRUE,FALSE,TRUE,FALSE,TRUE),nrow=3) > x[,1] [,2] [,3] [1,] TRUE FALSE TRUE [2,] FALSE TRUE FALSE [3,] TRUE FALSE TRUE> ifelse(x, 1, 0)[,1] [,2] [,3] [1,] 1 0 1 [2,] 0 1 0 [3,] 1 0 1 Sarah On Wed, Jul 20, 2011 at 11:16 AM, Julian TszKin Chan <cjulian at bu.edu> wrote:> Hi all, > > Suppose I have a matrix of logical value: > > x<-matrix(c(TRUE,FALSE,TRUE,FALSE,TRUE,FALSE,TRUE,FALSE,TRUE),nrow=3) > > I would like to change the value of FALSE to 0 and TRUE to 1. An > obvious way to do it is : > y<-as.numeric(x) > > However this method doesn't keep the dim of x. I also need to copy the > dim information to y too. > attributes(y)<-attributes(x) > > Is this a correct way to do it in R? Is there any single step function > which can do the something? Thanks > > > Regards, > TszKin Julian >-- Sarah Goslee http://www.functionaldiversity.org
Joshua Wiley
2011-Jul-20 15:40 UTC
[R] transforming a matrix of logical to 0 and 1 while keeping the dim of matrix
Hi, I am not sure about "correct", but R stores logical values TRUE/FALSE as 1/0 already so simply changing the mode would suffice: mode(x) <- "numeric" alternately x + 0 HTH, Josh On Wed, Jul 20, 2011 at 8:16 AM, Julian TszKin Chan <cjulian at bu.edu> wrote:> Hi all, > > Suppose I have a matrix of logical value: > > x<-matrix(c(TRUE,FALSE,TRUE,FALSE,TRUE,FALSE,TRUE,FALSE,TRUE),nrow=3) > > I would like to change the value of FALSE to 0 and TRUE to 1. An > obvious way to do it is : > y<-as.numeric(x) > > However this method doesn't keep the dim of x. I also need to copy the > dim information to y too. > attributes(y)<-attributes(x) > > Is this a correct way to do it in R? Is there any single step function > which can do the something? Thanks > > > Regards, > TszKin Julian > > ______________________________________________ > 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. >-- Joshua Wiley Ph.D. Student, Health Psychology University of California, Los Angeles https://joshuawiley.com/