0

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))
Eric Tim
  • 31
  • 8
  • Maybe you can use `Sys.Date()` instead of `date()`. See also [Convert character to class Date](https://stackoverflow.com/questions/4310326/convert-character-to-class-date) – Henrik Mar 18 '21 at 15:35
  • 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 Mar 18 '21 at 15:48

1 Answers1

1

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

fvall
  • 121
  • 1
  • 5
  • This works great! What is the "%c" doing? Looking at the documentation you linked it looks to me like it is about century, even though it's obviously not. – Eric Tim Mar 18 '21 at 15:52
  • Not really, lower %c is diff from caps %C. It should your locale specific time. I had nasty experiences when ignoring locale settings. %c Date and time. Locale-specific on output, "%a %b %e %H:%M:%S %Y" on input. – fvall Mar 18 '21 at 16:02