I noticed already a couple of times that working with dates doesn\'t allow for using the usual tricks in R. Say I have a dataframe Data with Dates (see below), and I want to
How about
str(as.data.frame(lapply(Data,as.Date,format="%d %B %Y")))
# 'data.frame': 6 obs. of 4 variables:
# $ Rep1:Class 'Date' num [1:6] 12898 12898 13907 13907 13907 ...
# $ Rep2:Class 'Date' num [1:6] 13278 13278 14217 14217 14217 ...
# $ Rep3:Class 'Date' num [1:6] 13600 13600 14340 14340 14340 ...
# $ Rep4:Class 'Date' num [1:6] 13831 13831 14669 14669 14669 ...
I think the most succinct way to do this is:
Data[] <- lapply(Data, as.Date,format="%d %B %Y")
This also nicely generalises to the case where not all columns are dates:
Data[date_col] <- lapply(Data[date_col], as.Date,format="%d %B %Y")
You can also simplify the date parsing with a couple of other packages
library(stringr)
library(lubridate)
Data[] <- lapply(Data, function(x) dmy(str_trim(x)))
which is a little more verbose, but has the advantage that you don't need to figure out the data format yourself.