as.character() Function in R with Example

A character object in R is used to interpret string values. We convert R objects into character values with the as.character() function. The as.character() function is used to convert a numeric object to a character object.

as.character() Function in R

The as.character() is an inbuilt function in R that generates a string representation of a provided argument. The as.character() function returns the string of 1’s and 0’s or a character vector of traits depending on the nature of the argument supplied.

Syntax

as.character(x)

Parameters

The as.character() function takes one argument that is an object of class fingerprint, featvec, or feature.

Return Value

The as.character() function returns the string of 1’s and 0’s or a character vector of features.

Example

data <- as.character(3.14)
data

Output

[1] "3.14"

In this example, we passed the floating value as an argument, and as.character() function converts into a character vector.

Convert a numeric object to a character

To convert a numeric object to a character in R, use the as.character() function. To create a vector in R, use the c() function. We will create two numeric vectors and convert those vectors into characters.

data1 <- c(11, 21, 31, 41)
data2 <- c(-11, 21, 1.5, -31)

as.character(data1)
as.character(data2)

Output

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

How to check character type in R

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

data1 <- 3.14
data2 <- c(-11, 21, 1.5, -31)

co1 <- as.character(data1)
co2 <- as.character(data2)

co1
co2

is.character(co1)
is.character(co2)

Output

[1] "3.14"
[1] "-11" "21" "1.5" "-31"
[1] TRUE
[1] TRUE

And we get the TRUE for both the output. That means we successfully converted a numeric object to a character vector.

Conclusion

R as.character() function converts the provided argument to character type. The as.character() and is.character() methods are generic functions. That is it for this tutorial.

Leave a Comment