2017-08-04 1 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でいくつかの本当に関与の機能を作成しようとしていると、これらの問題は、あなただけのdata.tablegetを使用し、文字列名によって列を取得しようとしている場合は、多く

+0

'is.Date'は基本関数ではありません、どのパッケージを読み込みましたか? –

+0

@Moody_Mudskipper lubridate – ATMA

+0

これらの質問を更新してください。私はあなたも 'data.table'と' dplyr'を使っていると思います。 –

答えて

1

を生じているように見える:

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 
関連する問題