2017-08-04 10 views
0

年、月または日付のいずれかのレベルに基づいて利益を集計しようとしています。私は別のファイルから集計のレベルを読んでおり、集計関数にそのファイルの値を渡したいが、それはエラーを投げている。Rの集計関数に動的値を渡す

library(lubridate) 

parameter <- read.csv("Parameter.csv",header = F,col.names = c("Option","Value")) 
head(parameter) 
orders <- read.csv("Orders_Data.csv") 
str(orders) 

orders$Order.Date <- as.POSIXct(orders$Order.Date,format ="%m/%d/%Y") 
orders$month = months(orders$Order.Date) 
orders$Year <- year(orders$Order.Date) 
head(orders$Year) 


option = as.character(parameter[1,2]) #option holds the level of aggregate 
option 

#[1] "Day" 

aggregate(Profit ~ Category + option ,data = orders, sum) 

エラーはここで

Error in model.frame.default(formula = Profit ~ Category + option, data = orders) : 
    variable lengths differ (found for 'option') 

が再生可能なデータが

option = "Year" 

aggregate(Profit ~ Category + option ,data = orders, sum) 

example = data.frame(date = sample(seq(as.Date('1999/01/01'), as.Date('2000/01/01'), by="day"), 24) 
        ,Profit = sample(seq(-200,1200),24) 
        , Department = sample(LETTERS[seq(from = 1, to = 26)],24)) 


example$Year <- year(example$date) 
head(example) 
aggregate(Profit ~ Department + option,data = example, sum) 

まだ同じエラー要するに

+0

小さな再現性の例と期待される出力を提供してください。単一の要素 'option'を使用している場合、それは機能しません。あなたはデータセットでそれを必要とするかもしれません – akrun

答えて

1

で、トランスフォーム、その後、手動で文字列式を作成する必要がありますですそれを実際の数式に変換し、それを集計に渡します。このよう

:しかし

option="Year" 
formula=as.formula(paste0("Profit ~ Department + ",option)) 
aggregate(formula,data = example, sum) 

、私はずっと容易になるだろうdata.tableを使用して感じる(かつ迅速に!):

library(data.table) 
example=data.table(example) 

example[,.(Profit=sum(Profit)),by=c("Department",option)] 
+0

それはとても良い&簡単だった –