Occasionally, I read in data from Microsoft Excel into R. In Excel, the date variables are formatted correctly (e.g. 31-Dec-2017). Following reading into R, the same date variable gets converted into another format (e.g. 2017-12-31).
A sample of my data frame (after being read into R) looks like the following:
df <- structure(list(ID = c("001", "002", "003", "004", "005"),
t1_date = structure(c(1490227200, 1508198400, 1511395200, 1527292800, 1485216000),
class = c("POSIXct", "POSIXt"), tzone = "UTC"),
t2_date = structure(c(1524009600, NA, NA, NA, 1523232000),
class = c("POSIXct", "POSIXt"), tzone = "UTC"),
t3_date = c(NA, NA, NA, NA, NA),
t4_date = c(NA, NA, NA, NA, NA),
t5_date = c(NA, NA, NA, NA, NA)),
.Names = c("ID", "t1_date", "t2_date", "t3_date", "t4_date", "t5_date"),
row.names = c(NA, -5L), class = c("tbl_df", "tbl", "data.frame"))
Using the t1_date variable as an example, I can individually convert each date column from the POSIXct class (which R selects for me) into the Date class and then changing the format using the following code:
df$t1_date <- as.Date(df$t1_date)
df$t1_date <- format(df$t1_date, "%d-%b-%Y")
However, I have many date columns and they may not be adjacent to one another in the data frame.
Normally, to solve such problems, I use the which and apply functions to select the relevant columns and apply the function to them:
df[, which(colnames(df) == "t1_date"):
which(colnames(df) == "t5_date")] <-
apply(df[, which(colnames(df) == "t1_date"):
which(colnames(df) == "t5_date")], 2, function(x) as.Date(x, format = "%d-%b-%Y"))
The above code resulted in NAs in all the date columns and I am unsure why. Even if I do not force the change in format, but convert the date columns from the POSIXct class to the Date class, the code still does not work (see below):
df[, which(colnames(df) == "t1_date"):
which(colnames(df) == "t5_date")] <-
apply(df[, which(colnames(df) == "t1_date"):
which(colnames(df) == "t5_date")], 2, as.Date)
My desired result is to convert the dates to a DD-MMM-YYYY format (e.g. 31-Dec-2017).
Help appreciated. Thanks!