How to Convert Character to Numeric Column in R DataFrame

To convert a character column to a numeric column in R DataFrame:

df$column_name <- as.numeric (df$column_name)

Example of Converting Character to Numeric Column in R DataFrame

Here is an example of converting the character ‘Price‘ column to a numeric column in R DataFrame:

# Create a DataFrame
df <- data.frame(
                Product = c("Laptop", "Printer", "Tablet"),
                Price = c("1200", "300", "450")
                )

# Display the original DataFrame
print("Original DataFrame:")
print(df)

# Print the data types before conversion
print("Data Types Before Conversion:")
str(df)

# Convert the Price column to numeric 
df$Price <- as.numeric (df$Price)

# Print the data types after conversion
print("Data Types After Conversion:")
str(df)

Note that the str(df) was added to print the data types of the columns before and after the conversion.

Here are the data types before and after the conversion of the ‘Price‘ column from character to numeric:

[1] "Original DataFrame:"

  Product Price
1  Laptop  1200
2 Printer   300
3  Tablet   450

[1] "Data Types Before Conversion:"
'data.frame':   3 obs. of  2 variables:
 $ Product: chr  "Laptop" "Printer" "Tablet"
 $ Price  : chr  "1200" "300" "450"


[1] "Data Types After Conversion:"
'data.frame':   3 obs. of  2 variables:
 $ Product: chr  "Laptop" "Printer" "Tablet"
 $ Price  : num  1200 300 450

As seen in the original DataFrame, the ‘Price‘ column had a character data type (as highlighted in yellow), but changed to numeric (as highlighted in green).

You may refer to the following guide for the steps to convert a numeric to a character column in R DataFrame.

Leave a Comment