What is the as.character() function in R?

Overview

The as.character() function in R converts a numeric object to a string data type or a character object. If the collection is passed to it as an object, it converts all the elements of the collection to a character or string type.

Syntax

as.character(x)

Parameter value

The as.character() function takes a single parameter value, x, which represents the numeric object that needs to be converted.

Return value

The as.character() function returns a string or a character object.

Code example 1

# calling the as.character() function over numeric objects
as.character(1)
as.character(2)
as.character(10)
as.character(0.5)
as.character(1 + 2)

Code explanation

We called the as.character() function on the numeric objects in the code written above.

Interestingly, the as.character() function can also be implemented on a vector object.

Code example 2

# creating our vector variables
myvector1 <- c(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
myvector2 <- c(10, 0.5, 2.5, -100)
# calling the as.character() function
as.character(myvector1)
as.character(myvector2)

Code explanation

  • Lines 2–3: We create the vector variables myvector1 and myvector2.
  • Lines 6–7: We call the as.character() function on the vector varaibles that we created.

Free Resources