0

I had the following code to change all columns starting with "DT" to Date format with mutate_at from dplyr

date_cols <- str_subset(names(df),'^DT')
df <- df %>%
  mutate_at(
    .vars= date_cols,
    .funs=list(~ as.Date(.,format = "%d%m%Y"))
  )

To do the same thing using data.table I wrote the following code (which works)

date_cols <- str_subset(names(df),'^DT')
for (column in date_cols) {
  df[,(column) := as.Date(df[[..column]],format = "%d%m%Y")]
}

The question is if there isn't a mutate_at equivalent in data.table which would avoid the explicit for loop? (Not really a problem, just curiosity)

bpbutti
  • 381
  • 1
  • 8
  • 1
    [How to apply same function to every specified column in a data.table](https://stackoverflow.com/questions/16846380/how-to-apply-same-function-to-every-specified-column-in-a-data-table) – Henrik Jul 05 '20 at 17:04
  • Thank @countorlok, simplifying the answer from that post a bit I was able to do it – bpbutti Jul 05 '20 at 17:06

1 Answers1

1

Based on a more complex answer from What is the equivalent of mutate_at (dplyr) in data.table? indicated by count orlok, I wrote the following code which works as I wanted

date_cols <- str_subset(names(df),'^DT')
df[,(date_cols) := lapply(.SD, function(x) as.Date(x,format = "%d%m%Y")), 
   .SDcols = date_cols]
bpbutti
  • 381
  • 1
  • 8