使用data.table向函数添加许多参数

时间:2017-08-04 17:23:33

标签: r data.table

我有以下数据,我正在尝试创建一个函数。

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

我真正的任务是涉及很多,但我有一些关于在函数中使用data.table的问题。这是我放在一起的快速功能。它检查了日期列,并在需要时对其进行了修复,并按帐户列汇总了数据。

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][]
}

当我运行此功能时,我收到以下错误。

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. 
    > 

任何人都可以帮助诊断此问题。 我试图用data.table创建一些真正涉及的函数,这些问题似乎出现了很多

1 个答案:

答案 0 :(得分:1)

如果您尝试按字符串名称获取列,请在get中使用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