To convert character to date column in R, you can use as.Date() function.
The following method shows how you can use it with syntax.
Method: Use as.Date() Function
as.Date(data)
Let’s first create data frame which having character to be converted to date.
# Create data frame
df <- data.frame(Start_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)
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
The following example shows how to convert character to date column of data frame in R.
Convert Character to Date Column Using as.Date() Function
Let’s see how we can use as.Date() function in R to convert character to date column of data frame.
# Create data frame
df <- data.frame(Start_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 date format
df$date <- as.Date(df$Start_date, format = "%Y-%m-%d")
# Print data frame
print(df)
Output:
Start_date Machine_name Value Reading date
1 2000-05-21 Machine1 108 110 2000-05-21
2 2000-05-22 Machine2 120 97 2000-05-22
3 2000-05-23 Machine1 135 91 2000-05-23
4 2000-05-24 Machine3 95 89 2000-05-24
5 2000-05-25 Machine2 98 80 2000-05-25
6 2000-05-26 Machine3 105 85 2000-05-26
As the output shows data frame in which data type of string is converted into date time format.