Reputation: 53
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))
Upvotes: 0
Views: 164
Reputation: 402
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
Upvotes: 1