To character or string type data into numeric data you can use as.numeric() function in R.
The following method shows how you can use it with syntax.
Method: Use as.numeric() Function
as.numeric(df$column_name)
Suppose we have data frame df which having multiple columns in it:
# 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 : chr "108" "120" "135" "95" ...
$ Reading : num 110 97 91 89 80 85
NULL
Here in the above code we created data frame and also check data type of each column of data frame.
The following example shows how to convert character to numeric column in R.
Convert Character to Numeric Column Using as.numeric() Function in R
Let’s see how we can example using as.numeric() function in R:
# 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 string to numeric format
df$Value <- as.numeric(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] "numeric"
Here the output shows data frame and data type of Value column of data frame whose data type we changed in above code.