R – Convert String to Integer
To convert String to Integer in R programming, call strtoi() function, pass the string and base values to this function. strtoi(string, base) returns the integer value of the given string with respect to the specified base.
In this tutorial, we will learn how to convert a string to integer in R, with examples.
Syntax of strtoi()
The syntax of strtoi() function is
strtoi(x, base=0L)
Parameter | Description |
---|---|
x | Character Vector. |
base | Base considered to convert given string to integer. Possible values for base are in the range [2, 36] |
If the string x has a suffix of 0
, and base is not specified exclusively, then the base is considered to be 8.
If the string x has a suffix of 0X
or 0x
, and base is not specified exclusively, then the base is considered to be 16.
Return Value
The function strtoi() returns an integer value created from the string x
, considering the base value of base
.
Examples
In the following program, we take a string in x
, and convert this string to integer using strtoi(), with default base value.
example.R
x <- "29"
result <- strtoi(x)
print(result)
print(typeof(result))
We print the type of result
as well, to demonstrate the type of the value returned by strtoi().
Output
[1] 29
[1] "integer"
Now, let us use take a hex value in string x
, and convert this string to integer using strtoi(), with base 16.
example.R
x <- "2A"
result <- strtoi(x, base=16)
print(result)
print(typeof(result))
Output
[1] 42
[1] "integer"
Let us take strings with suffix values of 0x and 0X, and convert them to integers using strtoi().
example.R
x <- "0x25"
result <- strtoi(x)
print(result)
x <- "0X2A"
result <- strtoi(x)
print(result)
Output
[1] 37
[1] 42
If the string has a suffix of 0
, and base is not specified, then the base of 8
is considered for conversion.
example.R
x <- "025"
result <- strtoi(x)
print(result)
Output
[1] 21
Conclusion
In this R Tutorial, we learned how to convert a string value to an integer in R language, using strtoi() function, with the help of examples.