R – Convert Logical Vector into Integer Vector
To convert a given logical vector into integer vector in R, call as.integer() function and pass the logical vector as argument to this function. as.integer() returns a new vector with the logical values transformed into integer values.
During conversion, logical value of TRUE would be converted to integer value of 1, and logical value of FALSE would be converted to integer value of 0. NA (missing value) remains NA, because NA is allowed in integer vector.
The syntax to use as.integer() to convert logical vector
v1 to integer vector
v2 = as.integer(v1)
In the following program, we take a logical vector in
v1, and convert this to integer vector using as.integer(). We print the returned integer vector from as.integer(), and print the type of vector obtained programmatically using typeof() function.
v1 <- c(TRUE, TRUE, FALSE) v2 <- as.integer(v1) print(v2) print(typeof(v2))
 1 1 0  "integer"
Now, let us take a logical vector with some NA values, and convert it into integer vector.
v1 <- c(TRUE, NA, NA, TRUE, FALSE) v2 <- as.integer(v1) print(v2) print(typeof(v2))
 1 NA NA 1 0  "integer"
In this R Tutorial, we learned how to convert a logical vector into integer vector, using as.integer() function, with the help of examples.