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 between 2 and 36 inclusive, 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 vectors
mystring1 <- c("A", "B")
mystring2 <- c("1", "2")
strtoi(mystring1)
strtoi(mystring2)

Code explanation

  • Lines 2–3: We create the string vector variables mystring1 and mystring2.
  • Lines 5–6: We implement the strtoi() function on both the variables mystring1 and mystring2, without specifying a base.

Note: Notice from the code output that the character string mystring1, which is not specified with a base value in the strtoi() function returned NA.

Code example 2

# creating strings
mystring1 <- 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 mystring1 and mystring3.
  • Lines 6–8: We implement the strtoi() function on the two variables, using different parameter values for each of them.

New on Educative
Learn to Code
Learn any Language as a beginner
Develop a human edge in an AI powered world and learn to code with AI from our beginner friendly catalog
🏆 Leaderboard
Daily Coding Challenge
Solve a new coding challenge every day and climb the leaderboard

Free Resources