Search code examples
rdataframeloops

Performing An Iterative Transformation with 2 Values While Creating a Named Column for Each Iteration in R


I would like to transform the sales column in each row, using the parameters in "addition" and "division" and then automatically create a named column that contains this transformation for that row value

Here is the sample data

set.seed(1)
time=seq(1:4)
sales=rpois(4,7)
addition_vec=c(0,5,10)
division_vec=c(1,2,3)


starter_df=data.frame(time,sales)

and here is what I would like to come out of it, but with the NA values populated with the relevant calculations for the named column. Calculations should be to add to sales by with the value in "addition_vec", and then divide the sum by the value in "division_vec"

enter image description here


Solution

  • The most straightforward way to do this would be to use two loops:

    for (a in addition_vec){
        for (d in division_vec){
            cname <- paste0("add_",a,"_div_",d)
            starter_df[cname] <- (starter_df$sales + a)/d 
        }    
    }
    
    starter_df
    

    This will result in the following outcome: enter image description here

    And possibly a bit more elegant:

    m <- matrix(outer(outer(starter_df$sales, addition_vec, "+"),division_vec, "/"),nrow=nrow(starter_df))
    colnames(m) <- paste0("add_",apply(expand.grid(addition_vec, division_vec), 1, paste, collapse="_div_"))
    
    starter_df <- cbind(starter_df,data.frame(m)) # overwrite original df
    

    This will result in the following outcome (the order of columns is different) enter image description here