What is the strtoi() function in R?
Overview
The strtoi() function in R is used to convert strings to integers according to the given base.
Syntax
strtoi(x, base = OL)
Parameter value
The strtoi() function takes the following parameter values:
x: This represents the character vector.base: This represents an integer between2and36inclusive, or zero (default) of which the string is to be converted to. This is an optional parameter.
Return value
The strtoi() function returns an integer vector of the same length as the character parameter value that is passed to it. It returns a NA (not available) value for character strings that are not specified with a base value.
Code example 1
# creating string vectorsmystring1 <- c("A", "B")mystring2 <- c("1", "2")strtoi(mystring1)strtoi(mystring2)
Code explanation
- Lines 2–3: We create the string vector variables
mystring1andmystring2. - Lines 5–6: We implement the
strtoi()function on both the variablesmystring1andmystring2, without specifying a base.
Note: Notice from the code output that the character string
mystring1, which is not specified with abasevalue in thestrtoi()function returnedNA.
Code example 2
# creating stringsmystring1 <- c("Hello", "World", "25C")mystring3 <- c("aaaa", "123", "BBB")strtoi(mystring1, 36L)strtoi(mystring3, 16L)
Code explanation
- Lines 2–3: We create the string vector variables
mystring1andmystring3. - Lines 6–8: We implement the
strtoi()function on the two variables, using different parameter values for each of them.