What is the as.character() Function in R

The as.character() function in R is “used to convert a numeric object to a string data type or a character object.

Syntax

as.character(x)

Parameters

x: It isnumeric object that needs to be converted.

Return Value

The as.character() function returns a string or a character object.

Example 1: Convert a numeric object to a character

To convert a numeric object to a character in R, use the “as.character()” function.

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"

Example 2: Using the as.character() function with vector

rv1 <- c(1, 2, 3, 4, 5)
rv2 <- c(10, 0.5, 2.5, -100)

as.character(rv1)
as.character(rv2)

Output

[1] "1" "2" "3" "4" "5"
[1] "10" "0.5" "2.5" "-100"

Example 3: 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

That’s it.

Leave a Comment