Home » How to Convert Numeric to Character in R (With Examples)

How to Convert Numeric to Character in R (With Examples)

by Erma Khan
spot_img

We can use the following syntax to convert a numeric vector to a character vector in R:

character_vector character(numeric_vector)

This tutorial provides several examples of how to use this function in practice.

Example 1: Convert a Vector from Numeric to Character

The following code shows how to convert a numeric vector to a character vector:

#create numeric vector
chars #convert numeric vector to character vector
chars character(chars)

#view character vector
chars

[1] "12" "14" "19" "22" "26"

#confirm class of character vector
class(chars)

[1] "character"

Example 2: Convert a Column from Numeric to Character

The following code shows how to convert a specific column in a data frame from numeric to character:

#create data frame
df frame(a = c('12', '14', '19', '22', '26'),
                 b = c(28, 34, 35, 36, 40))

#convert column 'b' from numeric to character
df$b character(df$b)

#confirm class of character vector
class(df$b)

[1] "character"

Example 3: Convert Several Columns from Numeric to Character

The following code shows how to convert all numeric columns in a data frame from numeric to character:

#create data frame
df frame(a = c('12', '14', '19', '22', '26'),
                 b = c('28', '34', '35', '36', '40'),
                 c = as.factor(c(1, 2, 3, 4, 5)),
                 d = c(45, 56, 54, 57, 59))

#display classes of each column
sapply(df, class)

          a           b           c           d 
  "numeric" "character"    "factor"   "numeric" 

#identify all numeric columns
numsnumeric)

#convert all numeric columns to character
df[ , nums] data.frame(apply(df[ , nums], 2, as.character))

#display classes of each column
sapply(df, class)

          a           b           c           d 
"character" "character"    "factor" "character" 

This code made the following changes to the data frame columns:

  • Column a: From numeric to character
  • Column b: Unchanged (since it was already numeric)
  • Column c: Unchanged (since it was a factor)
  • Column d: From numeric to character

By using the apply() and sapply() functions, we were able to convert only the numeric columns to character columns and leave all other columns unchanged.

Additional Resources

The following tutorials explain how to perform other common conversions in R:

How to Convert Character to Numeric in R
How to Convert Character to Factor in R
How to Convert Factor to Character in R
How to Convert a Character to a Timestamp in R

spot_img

Related Posts