Reputation: 57
I have used the internet and tried different options but not able to convert the string to date format
Sample Values in my data frame named as A in vector date
Date
"1-Sep"
"2-Sep"
"3-Sep"
"4-Sep"
"5-Sep"
"6-Sep"
x<-A$Date
A$Date_2<-as.POSIXct(paste("01-", x, sep = ""), format = "%d-%b-%y")
I want the output in "2020-09-28" format
Upvotes: 0
Views: 55
Reputation: 887911
We can use dmy
library(lubridate)
A$Date_2 <- dmy(A$V1, truncated = 2)
A$Date_2
#[1] "2020-09-01" "2020-09-02" "2020-09-03" "2020-09-04" "2020-09-05" "2020-09-06"
A <- structure(list(V1 = c("1-Sep", "2-Sep", "3-Sep", "4-Sep", "5-Sep",
"6-Sep")), row.names = c(NA, -6L), class = "data.frame")
Upvotes: 0
Reputation: 39613
Try this. Maybe you need to add the year as it looks like you have day and month in your strings. Then, you can use as.Date()
function:
#Code
A$Date_2<-as.Date(paste("2020-", x, sep = ""), format = "%Y-%d-%B")
Output:
V1 Date_2
1 1-Sep 2020-09-01
2 2-Sep 2020-09-02
3 3-Sep 2020-09-03
4 4-Sep 2020-09-04
5 5-Sep 2020-09-05
6 6-Sep 2020-09-06
Some data used:
#Data
A <- structure(list(V1 = c("1-Sep", "2-Sep", "3-Sep", "4-Sep", "5-Sep",
"6-Sep")), row.names = c(NA, -6L), class = "data.frame")
Upvotes: 2