R Basic

What is as.character() Function in R

as.character()

The as.character() is a generic function in R that converts any type of object to a character object. If you pass complex data types such as lists or data frames to this function, it will convert the whole structure into a character object.

It has different internal methods to handle different types of input objects. For example, it will handle simple data types like numeric vectors or factors differently than complex types like lists or data frames.

Why do we want to convert any type into a character

Whether you want to manipulate strings (character vectors) or combine different data type values into a character object, you need to convert all the types under one umbrella, and that is “character.

For example, if you want to concatenate data, you have to use the paste() function, and the paste() function requires input objects to be string or character objects. That is why you need to convert any type of data into characters. This is precisely where as.character() function proves its utility.

Syntax

as.character(obj)

Parameters

Name Value
obj It is an input object that will be converted to a character string.

Return Value

It returns a character object.

Numeric to character

numeric_vector <- c(11, 21, 31, 41)

as.character(numeric_vector)

Output

[1] "11" "21" "31" "41"

We defined a numeric vector, and using this function, we converted it into a character vector.

To check the character type, use the is.character() function. It returns TRUE if the argument is of character type; otherwise returns FALSE.

vec <- c(11, 21, 31, 41)

co <- as.character(vec)

co

is.character(co)

Output

[1] "11" "21" "31" "41"
[1] TRUE

When working with dates and times, this function can be used, but it’s often preferable to use strftime() for more control over the format.

Logical to Character

logical_vec <- TRUE
char_logical_vec <- as.character(logical_vec)

# Printing the results
print(logical_vec)
print(char_logical_vec)

# Printing the types
print(class(logical_vec))
print(class(char_logical_vec))

Output

[1] TRUE
[1] "TRUE"

[1] "logical"
[1] "character"

Factor to Character

When you pass factor to the as.factor() function, it will convert factor levels to string, not the underlying integer codes.

# Creating a factor
factor_val <- factor(c("ann", "emma", "barry"))
print(factor_val)
print(class(factor_val))

# Converting the factor to a character vector
char_vector <- as.character(factor_val)
print(char_vector)
print(class(char_vector))

Output

[1] ann emma barry
Levels: ann barry emma
[1] "factor"

[1] "ann" "emma" "barry"
[1] "character"

Date to Character

date <- as.Date("2024-12-24")
print(date)
print(class(date))

char_date <- as.character(date)
print(char_date)
class(char_date)

Output

[1] "2024-12-24"
[1] "Date"

[1] "2024-12-24"
[1] "character"

List to Character

The “list” is a complex data type and it consists of individual elements of different types. Although we can directly pass the list to the this function, it is not recommended because the character representation might not be directly helpful for data analysis, but it can be helpful for display or storage.

list_val <- list(21, "Krunal", TRUE)
print(list_val)
print(class(list_val))

char_list <- as.character(list_val)
print(char_list)
class(char_list)

Output

You can see that it converted the whole list data structure to character.

To efficiently handle character conversion, we need to iterate through the list and convert each element to a character vector using this function.

list_val <- list(21, "Krunal", TRUE)
print("------Before conversion------")
print(list_val)

# handle the as.character list element by element
list_val <- lapply(list_val, as.character)
print("------After conversion------")
print(list_val)

Data Frame to Character

The data frame is also a complex data type, and the as.character() function converts the whole data frame structure into a character.

df <- data.frame(x = 1:3, y = c("a", "b", "c"))
class(df)

char_df <- as.character(df)
class(char_df)

Output

[1] "data.frame"

[1] "character"

And we got an entire data frame as a single character vector.

Combining Data Types

Let’s create a new column from a data frame which will be the combination of other columns using the as.character() function.

df <- data.frame(
  id = 1:3,
  category = factor(c("A", "B", "A")),
  value = c(10, 20, 30),
  date = as.Date(c("2024-01-01", "2024-02-01", "2024-03-01"))
)

df$combined_values <- paste(
 as.character(df$id),
 as.character(df$category),
 as.character(df$value),
 as.character(df$date),
 sep = "-"
)

print(df)

Output

That’s all!

Recent Posts

R scale(): Scaling and Centering of Matrix-like Objects

The scale() function in R centers (subtracting the mean) and/or scales (dividing by the standard…

2 weeks ago

file.rename(): Renaming Single and Multiple Files in R

To rename a file in R, you can use the file.rename() function. It renames a…

3 weeks ago

R prop.table() Function

The prop.table() function in R calculates the proportion or relative frequency of values in a…

3 weeks ago

exp() Function: Calculate Exponential of a Number in R

The exp() is a built-in function that calculates the exponential of its input, raising Euler's…

3 weeks ago

R split() Function: Splitting a Data

The split() function divides the input data into groups based on some criteria, typically specified…

1 month ago

colMeans(): Calculating the Mean of Columns in R Data Frame

The colMeans() function in R calculates the arithmetic mean of columns in a numeric matrix,…

1 month ago