Patrick
Patrick

Reputation: 13

Turning a R date value from a character class into a date class

My problem is that I am importing a CSV file, and trying to get R to recognize the date column as dates and format them as such.

So far I have achieved to replace the format seen below "#yyyy-mm-dd#" with the integer date value in R.

But when I check the class before and after the transformation it still says "character".

I need the column to be recognized as a date class so that I can use it for forecasting. But

DemandCSV <- read_csv("C:/Users/pth/Desktop/Care/Demand.csv")
nrow <- nrow(DemandCSV)
for(i in 1:nrow){
  DemandCSV[i,1] <-as.Date(ymd(substr(DemandCSV[i,1], 2, 11)))
}
DemandCSV[,1] <- format(DemandCSV[,1], "%Y-%m-%d")

enter image description here enter image description here

Figured out an inelegant solution (turns out it was not a solution)

DemandCSV <- read_csv("C:/Users/pth/Desktop/Care/Demand.csv")
nrow <- nrow(DemandCSV)
for(i in 1:nrow){
  DemandCSV[i,1] <-as.Date(ymd(substr(DemandCSV[i,1], 2, 11)))
  DemandCSV[i,1] <- format(as.Date(as.numeric(DemandCSV[i,1],origin = "01-01-1970")), "%Y-%m-%d")}
DemandCSV %>% pad %>% fill_by_value(0)

Upvotes: 0

Views: 53

Answers (2)

Ben Bolker
Ben Bolker

Reputation: 226087

Does including the "#" in the format string solve your problem?

data <- c("#2019-09-23#", "#2019-09-24#", "#2019-09-25#")
a <- as.Date(data,format="#%Y-%m-%d#")

or

DemandCSV <- data.frame(date=
 c("#2019-09-23#", "#2019-09-24#", "#2019-09-25#"))
mutate_at(DemandCSV,"date",as.Date,format="#%Y-%m-%d#")

Upvotes: 2

Dirk is no longer here
Dirk is no longer here

Reputation: 368191

Maybe simpler to

  1. Substitute out the #
  2. Rely on anydate from the anytime package

Demo:

R> data <- c("#2019-09-23#", "#2019-09-24#", "#2019-09-25#")
R> anytime::anydate(gsub("#", "", data))
[1] "2019-09-23" "2019-09-24" "2019-09-25"
R> 

Upvotes: 1

Related Questions