2017-08-04 46 views
0

我有以下数据并试图创建一个函数。使用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一些真正参与功能,这些问题似乎出现了很多

+0

'is.Date'不是一个基函数,你加载了什么包? –

+0

@Moody_Mudskipper lubridate – ATMA

+0

请更新你的问题,我认为你也使用'data.table'和'dplyr' –

回答

1

如果你想获得一个字符串名称的列,只需用getdata.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