I would like to assign a trained model object to a data.table column so then I can work with it and assign it as I want. I have the following example data:
category min_price max_price avg_price avg_total_cost max_price_total_cost avg_quantity stores_year upc_sales_year match
1: HYGIENE PRODUCT 7.98 21.00 15.44070 21.16016 384.96 5.421875 58 128 1
2: TEA 0.60 107.50 11.30844 21.31594 107.50 13.984375 30 64 0
3: ENDULCORANTS 0.60 28.00 11.72000 30.60000 40.00 14.600000 3 5 1
4: VEGETABLES/FRUITS 6.00 13.50 11.58273 85.67364 234.00 10.363636 8 11 0
5: AUTO PARTS 29.76 38.88 34.91000 34.91000 38.88 4.500000 4 4 1
6: CANDY 10.60 46.00 31.95703 41.04363 2627.64 3.499127 207 573 1
and I have the following code:
library(randomForest)
library(caret)
library(data.table)
rand.tree.predictions <- function(dfexternal) {
data <- copy(dfexternal)
setDT(data)
train.data <- data[
match == 1,
.(min_price, max_price, avg_price, avg_total_cost, max_price_total_cost, avg_quantity, stores_year, upc_sales_year)
]
test.data <- data[
match == 0,
.(upc_code, min_price, max_price, avg_price, max_price_total_cost, avg_quantity, stores_year, upc_sales_year)
]
model <- train(avg_total_cost ~ min_price + max_price + avg_price + max_price_total_cost + avg_quantity + stores_year + upc_sales_year,
data = train.data,
method = 'rf',
trControl = trainControl(method = 'cv', number = 5)
)
#test.data$avg_total_cost_predicted <- predict(model, newdata = test.data)
#predict(model, newdata = test.data)
#result <- predict(model, newdata = test.data)
return(model)
}
where I define a function that trains the model and returns the trained model. However when I run it as follows:
reference.prices[, model := rand.tree.predictions(.SD)), by = category]
returns the following error:
Error in `[.data.table`(reference.prices, , `:=`(model, list(rand.tree.predictions(.SD))), :
Supplied 23 items to be assigned to group 1 of size 64 in column 'model'. The RHS length must either be 1 (single values are ok) or match the LHS length exactly. If you wish to 'recycle' the RHS please use rep() explicitly to make this intent clear to readers of your code.
the model object is a list but I don't understand the reason it throws that exception.