dimanche 31 janvier 2016

Creating a new column with a function's output, row by row

I have a data frame with a column of values (CVT_revenue$V4) ranging from 1 to 100. I want to apply a function to each of the values in the column and create a new column with the function's output. For example, if CVT_revenue$V4 had 45 in its first row, I would want the function to perform the calculation in the first else if statement, then put the output into the first row of the new column.

This is what I've tried:

actualRevenues <- function(df, column){
  for (i in 1:nrow(df)){
    if (column[i] < 33){
      df$actualRevenue <- (column[i] * 22000 + 300000)
    } else if(column[i] > 32 & column[i] < 67){
      df$actualRevenue <- ((column[i] - 32) * 33000000 + 1000000)
    } else {
      df$actualRevenue <- ((column[i] - 66) * 9090909 + 100000000)
    }
      }
}
actualRevenues(CVT_revenue, CVT_revenue$V4)

I think mapply might be the easiest way to accomplish this, but I'm not sure why my code isn't working. If I put a print statement after the else statement, I can see that it's calculating the same value over and over again. This is a snippet from the printed results:

    [1] 5.95e+08 5.95e+08 5.95e+08 5.95e+08 5.95e+08 5.95e+08 5.95e+08 5.95e+08 5.95e+08
  [10] 5.95e+08 5.95e+08 5.95e+08 5.95e+08 5.95e+08 5.95e+08 5.95e+08 5.95e+08 5.95e+08
  [19] 5.95e+08 5.95e+08 5.95e+08 5.95e+08 5.95e+08 5.95e+08 5.95e+08 5.95e+08 5.95e+08
  [28] 5.95e+08 5.95e+08 5.95e+08 5.95e+08 5.95e+08 5.95e+08 5.95e+08 5.95e+08 5.95e+08

Thanks for your help.

Aucun commentaire:

Enregistrer un commentaire