Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does the condition in if statements get coerced to logical?

Tags:

r

The documentation for if says that the condition should be (emphasis mine):

A length-one logical vector that is not NA. Conditions of length greater than one are currently accepted with a warning, but only the first element is used. An error is signalled instead when the environment variable _R_CHECK_LENGTH_1_CONDITION_ is set to true. Other types are coerced to logical if possible, ignoring any class.

How is the coercion done, and what does it mean "ignoring any class"?

For example, the expression list(1) can be explicitly coerced to TRUE with as.logical, and is implicitly considered TRUE with equality comparisons:

> as.logical(list(1))
[1] TRUE
> list(1) == TRUE
[1] TRUE

Why, then, does the following fail?

> if (list(1)) print("Passed test!")
Error in if (list(1)) print("Passed test!") : 
  argument is not interpretable as logical
like image 699
C. Braun Avatar asked Nov 07 '22 19:11

C. Braun


1 Answers

That happen because if in R uses the primary object class, in your example the primary object is the list instead of their contents, when you use as.logical the internal values are converted to logical returning an array.

a = list(x = 1, y = 0)
as.logical(a) # TRUE FALSE

Only if the primary object value is numeric or some special strings can be converted to logical by default.

if("true") "ok" # ok
if(-1) "ok" # ok

val = 1
class(val) = "test"
attr(a, "something") = 0

if(val) "ok" # ok

[EDIT_1]

Another nice thing to explain is about factors: The factor isn't work as a character array but as an array of numbers. These numbers refers about the value "flag".

val = factor("TRUE", "FALSE")
as.numeric(val) # 1 (for TRUE), 2 (for FALSE)
like image 62
Pedro Henrique S Avatar answered Nov 15 '22 11:11

Pedro Henrique S