rkraft
rkraft

Reputation: 555

Code Refactoring - Code Improvement suggestions

Problem: I have the following function which I want to write in a dry'er way. Does anyone of you have a suggestion how to improve these functions? Essentially, the function takes a date object and extracts the week, quarter, month and year in additional columns.

Many thanks!!

library(data.table)
library(tsibble)

determine_entry_date_aggregations <- function(data, date_col = "OBS_DATE"){
  data[, ":="(entry_date_quarter = yearquarter(get(date_col)),
              entry_date_week = format(get(date_col), "%G W%V"),
              entry_date_month = yearmonth(get(date_col)),
              entry_date_year = year(get(date_col)))]
}
determine_finish_date_aggregations <- function(data, date_col = "FIN_DATE"){
  data[, ":="(finish_date_quarter = yearquarter(get(date_col)),
              finish_date_week = format(get(date_col), "%G W%V"),
              finish_date_month = yearmonth(get(date_col)),
              finish_date_year = year(get(date_col)))]
}

Upvotes: 0

Views: 36

Answers (1)

chinsoon12
chinsoon12

Reputation: 25225

This is probably a matter of style. Here is one option to store the functions in a list and passing in date_col as a string to .SDcols:

funlist <- list(date_quarter=yearquarter, 
    date_week=function(x) format(x, "%G W%V"), 
    date_month=yearmonth, 
    date_year=year)

determine_date_aggregations <- function(data, date_col="FIN_DATE", out_col="finish"){
    data[, paste(out_col, names(funlist), sep="_") := 
        lapply(funlist, function(f) f(.SD[[1L]])), .SDcols=date_col]
}

Or using set instead of :=:

determine_date_aggregations <- function(data, date_col="FIN_DATE", out_col="finish") {
    for (f in names(funlist)) {
        set(data, j=paste(out_col, f, sep="_"),
            value=funlist[[f]](data[[date_col]]))
    }
}

Upvotes: 1

Related Questions