To convert a numeric column to a character column in R DataFrame:
df$column_name <- as.character(df$column_name)
Example of Converting Numeric to Character Column in R DataFrame
Here is an example of converting the numeric ‘Age‘ column to a character column in R DataFrame:
# Create a sample DataFrame df <- data.frame( Name = c("Jon", "Bill", "Maria"), Age = c(25, 32, 28) ) # Display the original DataFrame print("Original DataFrame:") print(df) # Print the data types before conversion print("Data Types Before Conversion:") str(df) # Convert the Age column to character df$Age <- as.character(df$Age) # 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 in the DataFrame before and after the conversion.
Here are the data types before and after the conversion of the ‘Age‘ column from numeric to character:
[1] "Original DataFrame:"
Name Age
1 Jon 25
2 Bill 32
3 Maria 28
[1] "Data Types Before Conversion:"
'data.frame': 3 obs. of 2 variables:
$ Name: chr "Jon" "Bill" "Maria"
$ Age : num 25 32 28
[1] "Data Types After Conversion:"
'data.frame': 3 obs. of 2 variables:
$ Name: chr "Jon" "Bill" "Maria"
$ Age : chr "25" "32" "28"
As seen in the original DataFrame, the ‘Age‘ column had a numeric data type (highlighted in yellow).
However, after the conversion, the ‘Age‘ column’s data type changed to character (highlighted in green).