What is the character() function in R?

Overview

The character() function in R is used to create character vectors. In simpler words, the character() function in R is used to create a character object type.

Syntax

character(x)

Parameter value

The character() function takes the parameter value x, which represents the number of characters that make up the character object’s length.

Code example

# implementing the character() function
myvector <- character(5)
# printing the charater object
myvector
# checking if is a character object
is.character(myvector)

Code explanation

  • Line 2: We create a character object of length 5, myvector, using the character() function.
  • Line 5: We print the variable called myvector.
  • Line 8: We check whether or not the object is of the specified character type, using the is.character() function.

Importance of the character() function

The character() function is very important in a situation where we want to initialize an empty character of a given length to a vector object and later on perform some modification on the vector object, such as adding a new component to it.

Code example

# creating a vector object of empty character
myvector <- character(0)
# printing the vector object
myvector
# to check the length of the vector object
length(myvector)
# to modify the oject by adding a new component
myvector[1] <- "Hi"
# printing the modified vector object
myvector
# to check the length of the new vector object
length(myvector)

Code explanation

  • Line 2: We create a vector object myvector with an empty character, using the character() function.
  • Line 5: We print the vector object called myvector.
  • Line 8: We obtain the length of the vector object.
  • Line 12: We modify the vector object myvector by adding a new character to the first index.
  • Line 15: We print the modified object.
  • Line 19: We obtain the length of the modified vector object.

Free Resources