How To Convert Type of Vector in R?
We use as.integer() function to convert a given logical vector or character vector into integer vector in R, by passing the logical or character vector as argument to this function. It will return a new vector with values transformed into the new integer values.
Logical value of TRUE is converted to integer value of 1, and FALSE is converted to integer value of 0. NA (missing value) remains NA, because NA is allowed in integer vector. String value (character) is converted into an integer value. It considers the special cases such as a base value of 16 if the number in string is preceded by 0x, or 0X.
Example 1 – Logical to integer:
m1 <- c(TRUE, NA, FALSE)
m2 <- as.integer(m1)
print(m2)
print(typeof(m2))
#output:
[1] 1 NA 0
[1] "integer"
Example 2 – String/Character to integer:
m1 <- c("1", "2", "0x44", "100", NA)
m2 <- as.integer(m1)
print(m2)
print(typeof(m2))
#output:
[1] 1 2 68 100 NA
[1] "integer"
Conclusion:
We use as.integer() function to convert a given logical vector or character vector into integer vector in R programming.
