Tom
Tom

Reputation: 15

calculate new column in dataframe or list using a function with column as param

I'm trying to calculate a new column with a user defined function that needs data from same row and a fixed value valid for all rows:

myfunc <- function(ds,colname,val1,col1,col2){
  # content of new column <colname> should be computed from:
  ds[colname] = val1 + ds[col1] * ds[col2] #   for each row of ds
  return(ds)
}

v1 = 2
data(mtcars) 
mt = head(mtcars) 
mt
                   mpg cyl disp  hp drat    wt  qsec vs am gear 

carb
Mazda RX4         21.0   6  160 110 3.90 2.620 16.46  0  1    4    4
Mazda RX4 Wag     21.0   6  160 110 3.90 2.875 17.02  0  1    4    4
Datsun 710        22.8   4  108  93 3.85 2.320 18.61  1  1    4    1
Hornet 4 Drive    21.4   6  258 110 3.08 3.215 19.44  1  0    3    1
Hornet Sportabout 18.7   8  360 175 3.15 3.440 17.02  0  0    3    2
Valiant           18.1   6  225 105 2.76 3.460 20.22  1  0    3    1
apply(mt,'newcol',v1,mt$wt,mt$qsec)
mt

What I would like to see in mt$newcol in first row is: 2 + 2.620 * 16.46 (-> 45.12) and all other rows similiar.

So, how can I send a fixed value (v1) and two values from each row to my function and store returned value in this row in a new column?

Thanks

Upvotes: 1

Views: 38

Answers (1)

Aleksandr
Aleksandr

Reputation: 1914

dplyr approach:

library(dplyr)

data(mtcars) 

myfunc <- function(ds, new_column, val1, col1, col2){

  name <- rownames(ds)
  ds <- ds %>% 
    mutate(!!as.name(new_column) := val1 + !!as.name(col1) + !!as.name(col2),
           car_name = name) %>% 
    select(car_name, mpg:!!as.name(new_column))

  return(ds)

}

head(
  myfunc(ds = mtcars,
         new_column = "new_column",
         val1 = 2, 
         col1 = "hp", 
         col2 = "vs")
)

output

           car_name  mpg cyl disp  hp drat    wt  qsec vs am gear carb new_column
1         Mazda RX4 21.0   6  160 110 3.90 2.620 16.46  0  1    4    4        112
2     Mazda RX4 Wag 21.0   6  160 110 3.90 2.875 17.02  0  1    4    4        112
3        Datsun 710 22.8   4  108  93 3.85 2.320 18.61  1  1    4    1         96
4    Hornet 4 Drive 21.4   6  258 110 3.08 3.215 19.44  1  0    3    1        113
5 Hornet Sportabout 18.7   8  360 175 3.15 3.440 17.02  0  0    3    2        177
6           Valiant 18.1   6  225 105 2.76 3.460 20.22  1  0    3    1        108

Upvotes: 1

Related Questions