To convert numeric to character column of data frame in R, you can use as.character() function.
The following method shows how you can do it with syntax.
Method: Use as.character() Function
as.character(df$column_name)
Let’s first create data frame and check data type of each column data frame:
# Create data frame
df <- data.frame(Start_date=as.Date(c("2000-05-21","2000-05-22","2000-05-23","2000-05-24","2000-05-25","2000-05-26")),
Machine_name = c("Machine1","Machine2","Machine1","Machine3","Machine2","Machine3"),
Value = c(108,120,135,95,98,105),Reading= c(110,97,91,89,80,85))
# Print data frame
print(df)
# print datatype
print(str(df))
Output:
Start_date Machine_name Value Reading
1 2000-05-21 Machine1 108 110
2 2000-05-22 Machine2 120 97
3 2000-05-23 Machine1 135 91
4 2000-05-24 Machine3 95 89
5 2000-05-25 Machine2 98 80
6 2000-05-26 Machine3 105 85
'data.frame': 6 obs. of 4 variables:
$ Start_date : Date, format: "2000-05-21" "2000-05-22" "2000-05-23" ...
$ Machine_name: chr "Machine1" "Machine2" "Machine1" "Machine3" ...
$ Value : num 108 120 135 95 98 105
$ Reading : num 110 97 91 89 80 85
NULL
The following example shows how to use as.character() function in R.
Using as.character() Function
Let’s see how we can convert numeric datatype to character datatype of column of data frame:
# Create data frame
df <- data.frame(Start_date=as.Date(c("2000-05-21","2000-05-22","2000-05-23","2000-05-24","2000-05-25","2000-05-26")),
Machine_name = c("Machine1","Machine2","Machine1","Machine3","Machine2","Machine3"),
Value = c(108,120,135,95,98,105),Reading= c(110,97,91,89,80,85))
# Change the datatype from numeric to character format
df$Value <- as.character(df$Value)
# Print data frame
print(df)
# print datatype
print(class(df$Value))
Output:
Start_date Machine_name Value Reading
1 2000-05-21 Machine1 108 110
2 2000-05-22 Machine2 120 97
3 2000-05-23 Machine1 135 91
4 2000-05-24 Machine3 95 89
5 2000-05-25 Machine2 98 80
6 2000-05-26 Machine3 105 85
[1] "character"
Here in the above code we change data type of Value column from numeric to character. As the output shows data frame and datatype of Value column of data frame.