I am trying to turn the code below, which already works, into a function.
A similar situation, dcast + DT, has already been disscused here! But i've wasnt able to solve the problem like that.
What I want to achieve is:
- Change only two arguments for a multiple lines of code, and
- Write the objects created by each line in the function to working directory
This is the code that works already:
result1 <- dcast(setDT(data), customer_id ~ paste0("num_of_oranges",period), value.var = "num_of_oranges", sum)
result2 <- dcast(setDT(data), customer_id ~ paste0("num_of_oranges",period) + paste0("SIGN_",sign), value.var = "num_of_oranges", sum)
result3 <- dcast(setDT(data), customer_id ~ paste0("num_of_oranges",period) + paste0("SIGN_",sign) + paste0("ORIGIN_",origin), value.var = "num_of_oranges", sum)
My attempt towards the function:
create.Feature <- function(col1, stat) {
test1 <- dcast(df, df[[id]] ~ paste0("col1",df[[period]]), value.var = df[["col1"]], stat)
return(test1)
test2 <- dcast(df, df[[id]] ~ paste0("col1",df[[period]]) + paste0("SIGN",df[[sign]]), value.var = df[["col1"]], stat)
return(test2)
test3 <- dcast(df, df[[id]] ~ paste0("col1",df[[period]]) + paste0("SIGN",df[[sign]]) + paste0("ORIGIN",df[[origin]]), value.var = df[["col1"]], stat)
return(test3)
And the call:
test_result <- create.Feature("num_of_oranges", sum)
I get the following error: Error in .subset2(x, i, exact = exact) : no such index at level 1
Anyone?