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() functionmyvector <- character(5)# printing the charater objectmyvector# checking if is a character objectis.character(myvector)
Code explanation
- Line 2: We create a character object of length
5,myvector, using thecharacter()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 charactermyvector <- character(0)# printing the vector objectmyvector# to check the length of the vector objectlength(myvector)# to modify the oject by adding a new componentmyvector[1] <- "Hi"# printing the modified vector objectmyvector# to check the length of the new vector objectlength(myvector)
Code explanation
- Line 2: We create a vector object
myvectorwith an empty character, using thecharacter()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
myvectorby 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.