ATMA
ATMA

Reputation: 1466

Adding many arguments to a function with data.table

I have the following data and am trying to create a function.

dat = structure(list(Account_Id = c(1L, 2L, 3L, 4L, 4L, 5L, 5L, 6L, 
                                    7L, 8L), Order_Date = c("10/03/16", "10/03/16", "10/03/16", "10/03/16", 
                                                            "10/03/16", "10/03/16", "10/03/16", "10/03/16", "10/03/16", "10/03/16"
                                    )), .Names = c("Account_Id", "Order_Date"), class = c("data.table", 
                                    "data.frame"), row.names = c(NA, -10L))

dat

The real task I have is a LOT more involved, but I have some questions about using data.table within a function. Here is the quick function that I put together. It checked the date column, fixes it if needed, and summarized the data by the account column.

Weekday_Check <- function(data_DT, 
                          acct_col = "Account_Id",
                          date_col = "Order_Date"){

   acct_col = eval(substitute(acct_col))
   date_col = eval(substitute(date_col))

   if(!is.Date(class(dat[,.(date_col)]))){
      dat[,.(date_col)]
      dat[,(date_col) :=  substitute(as.Date(date_col))]
   } 

   dat[,list(Total=.N),by=date_col][]
}

When I run this function, I get the following error.

Weekday_Check(dat, 
              acct_col = "Account_Id",
              date_col = "Order_Date")



     Error in `[.data.table`(dat, , `:=`((date_col), substitute(as.Date(date_col)))) : 
      RHS of assignment is not NULL, not an an atomic vector (see ?is.atomic) and not a list column. 
    > 

Can anyone help in diagnosing this issue. I'm trying to create some really involved functions with data.table and these issues seem to arise a lot

Upvotes: 0

Views: 121

Answers (1)

akuiper
akuiper

Reputation: 215117

If you are trying to get the column by a string name, just use get in data.table:

Weekday_Check <- function(data_DT, acct_col = "Account_Id", date_col = "Order_Date"){
    # You may want to copy the data.table over to avoid side effects
    dat <- copy(data_DT)   

    # get a column with string name use [[]] or get     
    if( class(dat[[date_col]]) != "Date" ){
        dat[, (date_col) := as.Date(get(date_col), "%m/%d/%y")]
    }         
    dat[, .(Total = .N), by = setNames(list(get(date_col)), date_col)]
}

Weekday_Check(dat)

#   Order_Date Total
#1: 2016-10-03    10

Upvotes: 1

Related Questions