DeduciveR
DeduciveR

Reputation: 1702

Setting date class to multiple data frame columns whose names are specified in a list

This seems like it should be easy, but I can't find an answer.

I wish to only convert specified variables to dates - in reality (not this example) there are many columns to convert to date class. I have specified those columns in a list that I've created manually as below. I'd then like to be able to set date class for just those columns.

Data:

library(lubridate)

date1 <- c("19/06/2012", "19/10/2012", "12/08/2012")
var1 <- c("harry", "sally", "dick")
date2 <- c("08/06/2012", "07/11/2012", "19/07/2012")
var2 <- c("london", "paris", "madrid")
date3 <- c("17/07/2012", "18/09/2012", "19/11/2012")

df <- data.frame(date1, var1, date2, var2, date3)

datecols <- list("df$date1", "df$date2", "df$date3")

This is where I think I'm going wrong, I make a function to set the dates:

setdates <- function(a) {
  a <- a %>%
    dmy(a)
}

...but neither lapply:

lapply(datecols, setdates)

...nor a for loop works

for (i in datecols) {
  setdates(i)
}

To which I get parsing errors.

Unfortunately I can't seem to find an answer and I think I'm making this harder than it need be.

Upvotes: 0

Views: 41

Answers (1)

Aur&#232;le
Aur&#232;le

Reputation: 12839

If you don't mind using dplyr, you could:

library(dplyr)
res <- mutate_at(df, vars(starts_with("date")), dmy)

#        date1  var1      date2   var2      date3
# 1 2012-06-19 harry 2012-06-08 london 2012-07-17
# 2 2012-10-19 sally 2012-11-07  paris 2012-09-18
# 3 2012-08-12  dick 2012-07-19 madrid 2012-11-19

What it does is: apply dmy to those columns in df that starts_with "date".

Upvotes: 2

Related Questions