R: can I do the following using the Zoom Out function (or another high-level function)?

I have a function that takes a data frame as input and additional arguments that define some type of change in the data frame. As a simple example:

col_with_ones <- function(df, col_name) {
  df[[col_name]] <- 1
  df
}

Is there a way I can use Reduce(or any other high level function) to apply a few changes to the data frame? for example, continuing the example above, can I use Reduceto do the following:

df <- data.frame(a = runif(10))
for (letter in letters[2:5]) {
  df <- col_with_ones(df, letter)
}

Greetings

+4
source share
1 answer

Pretty simple:

Reduce(col_with_ones, letters[2:5], init = df)
+8
source

All Articles