Home > other >  How do I create a function with 3 argument of which 1 argument specifying two columns(in r)?
How do I create a function with 3 argument of which 1 argument specifying two columns(in r)?

Time:10-28

Make a function that takes a dataframe as argument, one argument specifying two columns to multiply as a numeric vector with length 2, and an argument that sets the name of the column to be created. The function should return the original dataframe with one extra column. The new column should contain the product of the two specified columns, and have the specified name.

Earlier performed steps:

set.seed(666)

produce <- data.frame(apples = rnorm(100), bananas = rnorm(100), carrots = rnorm(100))

CodePudding user response:

dt_prod <- function(dt, cols, name) {
     dt[[name]] <- dt[[cols[1]]] * dt[[cols[2]]]
}
  • Related