0

I am new to R. I want to confirm if my understanding of the concept is correct.

While working with logical operator OR I am unable to understand the below output. Case 1 has result "false" when both the second elements as 0 while it is "true" when these are numbers >0. Is this because 0 is always considered as "FAlse" and in this case both these values are "false"?

Case 1

v <- c(3,0,TRUE,2+2i)
t <- c(4,0,FALSE,2+3i)
print(v|t)
#[1]  TRUE FALSE  TRUE  TRUE

Case 2

v <- c(3,0,TRUE,2+2i)
t <- c(3,0,FALSE,2+3i)
print(v|t)
#[1]  TRUE FALSE  TRUE  TRUE
Sotos
  • 51,121
  • 6
  • 32
  • 66
  • 2
    You should read the documentation. Numeric values other than 0 are converted to TRUE if used as logical values – talat May 26 '17 at 10:27
  • Have a look at https://stackoverflow.com/questions/5681166/what-evaluates-to-true-false-in-r for more details – airos May 26 '17 at 10:28

2 Answers2

2

You are doing an elementwise logical comparison of both vectors v and t. And since any number > 0 evaluates to TRUE if converted to logical you are getting this output. (please also note the comment below)

You can think of this happenig in the background (for case 1):

   as.logical(3) | as.logical(4)
   as.logical(0) | as.logical(0)
            TRUE | TRUE
as.logical(2+2i) | as.logical(2+2i)

which yields our output:

TRUE FALSE TRUE TRUE
maRtin
  • 6,336
  • 11
  • 43
  • 66
1

R considers TRUE as 1 and FALSE as 0. Your understanding is correct. You have an elementwise checking and in the case where v[2]=0 and t[2]=0, R understands: 0 | 0 thus 0, i.e. FALSE OR FALSE = FALSE.

You can check this by changing one of the 0 inputs (v[2]=0 and t[2]=0) to something !=0.

As a comment though: you have to take into account that you can not use c() to create variables with different classes in them. R interprets all the inputs that you provide as complex numbers in this case. I mean that the TRUE is converted to 1+0i and the FALSE to 0+0i (check the: print(v) >v [1] -3+0i 0+0i 1+0i 0+2i)

NpT
  • 451
  • 4
  • 11