R – Convert Character Vector into Integer Vector
To convert a given character vector into integer vector in R, call as.integer()
function and pass the character vector as argument to this function. as.integer()
returns a new vector with the character values transformed into integer values.
During conversion, each string value is converted into an integer value. It considers the special cases like considering a base value of 16 if the number in string is preceded by 0x, or 0X.
Syntax
The syntax to use as.integer()
to convert character vector v1
to integer vector v2
is
v2 = as.integer(v1)
Examples
In the following program, we take a character 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.
Example.R
v1 <- c("1", "2", "0x44", "89")
v2 <- as.integer(v1)
print(v2)
print(typeof(v2))
Output
[1] 1 2 68 89
[1] "integer"
If there are NA values in the given character vector, then they remain unchanged with respect to their presence in the resulting vector from as.integer().
Example.R
v1 <- c("1", "2", NA)
v2 <- as.integer(v1)
print(v2)
print(typeof(v2))
Output
[1] 1 2 NA
[1] "integer"
If there are any string values which cannot be converted into a valid integer, then NA would be introduced for the respective value by coercion.
Example.R
v1 <- c("1", "2", "abc")
v2 <- as.integer(v1)
print(v2)
print(typeof(v2))
The third value "abc"
in vector v1
cannot be converted to a valid number. Therefore, the third element in the resulting vector would be NA
.
Output
[1] 1 2 NA
[1] "integer"
Conclusion
In this R Tutorial, we learned how to convert a character vector into integer vector, using as.integer() function, with the help of examples.