# [R] transforming a matrix of logical to 0 and 1 while keepin

(Ted Harding) ted.harding at wlandres.net
Wed Jul 20 18:18:00 CEST 2011

```It is easier and more straightforward than any of the suggestions
so far. Simply multiply the matrix by 1, or add 0 to it:

x<-matrix(c(TRUE,FALSE,TRUE,FALSE,TRUE,FALSE,TRUE,FALSE,TRUE),nrow=3)

1*x
#      [,1] [,2] [,3]
# [1,]    1    0    1
# [2,]    0    1    0
# [3,]    1    0    1

0+x
#      [,1] [,2] [,3]
# [1,]    1    0    1
# [2,]    0    1    0
# [3,]    1    0    1

Reason: When a logical value takes part in a numeric expression,
it is automatically coerced to numeric (0 or 1).

As the night-club bouncer said to the un-dressed clubber:
"We're not letting you in just wearing Naked Truth.
You've got to put on a proper black suit or white suit."

Ted.

On 20-Jul-11 15:40:49, Joshua Wiley wrote:
> 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
>> 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/
>
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help