Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why doesn't if ("T") throw an error even though "T" is not a logical vector?

Tags:

r

I stumbled upon this when I tried to find out why some function I wrote gave unexpected output.

> if ("T") print("why?")
[1] "why?"

Why does this work instead of giving out an argument is not interpretable as logical error? That is what happens to every other string passed to if, except "T", "F", "TRUE" and "FALSE".

According to the help page of if, the condition inside the brackets must be a logical vector, but

> is.logical("T")
[1] FALSE

How does that go together? How does if evaluate the condition, is there anything happening secretly that converts "T" to T?

like image 698
Hekla Avatar asked Sep 26 '18 17:09

Hekla


People also ask

What is the difference between is vector () and is numeric () functions?

numeric is a general test to check whether a vector is numeric or not. It will return TRUE only if the object passed to it is a vector and consists of only numeric data. Whereas, is. vector tests whether the object is a vector or not.

What functions from the Readr package allows you to turn a string into a logical integer and double vector?

What functions from the readr package allow you to turn a string into logical, integer, and double vector? The functions parse_logical, parse_integer, and parse_number.

How many values can be in a vector?

For integers vectors, R uses a 32-bit representation. This means that it can represent up to 232 different values with integers.

What is augmented vector in R?

Atomic vectors and lists are the building blocks for other important vector types like factors and dates. I call these augmented vectors, because they are vectors with additional attributes, including class. Because augmented vectors have a class, they behave differently to the atomic vector on which they are built.


1 Answers

Because as.logical converts a limited number of strings to logical:

as.logical attempts to coerce its argument to be of logical type. For factors, this uses the levels (labels). Like as.vector it strips attributes including names. Character strings c("T", "TRUE", "True", "true") are regarded as true, c("F", "FALSE", "False", "false") as false, and all others as NA.

The help file for if states that coercion takes place, but not how:

Other types are coerced to logical if possible, ignoring any class.

like image 74
James Avatar answered Oct 29 '22 07:10

James