Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I have a function which takes as inputs a data frame and additional arguments which determine some type of change to 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 multiple changes to a dataframe? e.g. continuing the example above, could I use Reduce to do the following:

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

Cheers

like image 375
user32259 Avatar asked Feb 14 '23 21:02

user32259


1 Answers

Quite simply:

Reduce(col_with_ones, letters[2:5], init = df)
like image 190
flodel Avatar answered Feb 17 '23 11:02

flodel