Home > Blockchain >  Passing a function to multiple dataframes at the same time
Passing a function to multiple dataframes at the same time

Time:02-28

I have 3 dataframes:

iris1<-iris[1:50, ]
iris2<-iris[51:100,]
iris3<-iris[101:150,]

And a simple function that takes the input of a dataframe and a column and multiplies that column by 100 and then returns the dataframe:

add_col<-function(df,colname)
{
df$newcol<-df [, colname]*100
return(df) 
}

I can then use that function on a dataframe to get the extra column added:

iris1<-add_col(df=iris1,colname="Sepal.Length")

How can I pass all the dataframes to this function rather than repeating the above 3x (1 for each dataframe?). I assume this is a problem that will use the apply family for functions but I can't work out how to do it.

CodePudding user response:

You can do:

new_list <- lapply(list(iris1, iris2, iris3), add_col, colname = "Sepal.Length")

Here, you will have the three data frames as list elements and you could get them back as real data frames by e.g.:

iris1_new <- new_list[[1]]

Or you can do the following to assign the new list elements to the global environment:

new_names <- c("iris1_new", "iris2_new", "iris3_new")
lapply(1:length(new_names), function(x) assign(x = new_names[x], value = new_list[[x]], envir = .GlobalEnv))

CodePudding user response:

Another possible solution, based on purrr::map:

library(tidyverse)

map(list(iris1, iris2, iris3), ~ add_col(.x, "Sepal.Length")) %>% 
  set_names(c("iris1", "iris2", "iris3")) %>% 
  list2env(.GlobalEnv)
  •  Tags:  
  • r
  • Related