Convert objects to character with as.character()
The as.character
function converts R objects to character data type. In this tutorial you will learn how to coerce vectors to character and how to check if an object is character or not.
Syntax and arguments
The syntax of the as.character
function is the following:
as.character(x, # Object to be coerced to character.
...) # Additional arguments if needed.
The function takes as argument an object (x
) to be coerced to character.
Usage
You can convert numbers, vectors or other R objects to character with the function. Consider, for instance, the following numeric vector:
x_numeric <- c(10, 156, -5, log(10))
x_numeric # 10.000000 156.000000 -5.000000 2.302585
This vector can be coerced to character with the as.character
function as follows:
x_character <- as.character(x_numeric)
x_character # "10" "156" "-5" "2.30258509299405"
Note that now the numbers are quoted and the number of decimals are different. If you need to transform the vector again to numeric you will need to use the as.numeric function.
Now consider that you have a date of class Date
and you want to transform it to character:
date <- as.POSIXct.Date(Sys.time())
date # "4654923-09-09 10:13:13 UTC"
You can also transform it to character with the as.character
function:
as.character(date) # "4654923-09-09 10:13:13.625"
Check if an object is of type character with is.character
If you have doubts whether your object is a character or not, you can use the is.character
function to check it. This function will return TRUE
if the object is character and FALSE
otherwise, as in the examples below.
is.character(3) # FALSE
is.character("R CODER") # TRUE
is.character(Sys.Date()) # FALSE
is.character(pi) # FALSE
Create empty character vector of a specified length with character
The last function related is the character
function, which takes a non-negative integer as input to specify the desired length of the vector. This function is useful, for instance, to pre-allocate data and fill a character vector of any length within a loop.
character() # character(0)
character(3) # "" "" ""