0
votes

I've got a dateframe with a lot of dates in it that were generated by the date() command in R, resembling the first dataframe below. On my computer with this version of R, the date values are formatted like this "Thu Mar 18 11:15:23 2021" - I believe this is all base R stuff.

I want to strip the weekday, the hours, minutes, and seconds away, and then transform it so that it looks like this "2021-03-18". My goal dataframe is the second dataframe below. I've tried various as.Date() or strftime functions to no avail.

df <- data.frame(date=c(date(),date()),value = c(1,2))
df <- data.frame(date =c("2021-03-18","2021-03-18"), value = c(1,2))
1
Maybe you can use Sys.Date() instead of date(). See also Convert character to class Date - Henrik
Definitely agree I should have used Sys.Date() instead of date(), but now the data has already been stored so the damage has been done. - Eric Tim

1 Answers

1
votes

If you don't need strings, you can skip the strftime call and only use as.Date

df <- data.frame(
  date=c(date(),date()),
  value = c(1,2),
  stringsAsFactors = FALSE
)

df$date <- strftime(as.Date(df$date, "%c"), "%Y-%m-%d")

https://stat.ethz.ch/R-manual/R-patched/library/base/html/strptime.html