2

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.

2 Answers 2

3

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))
Sign up to request clarification or add additional context in comments.

Comments

1

Another possible solution, based on purrr::map:

library(tidyverse)

x <- c("iris1", "iris2", "iris3")

map(map(x, ~ as.symbol(.x) %>% eval),
    ~ add_col(.x, "Sepal.Length")) %>%
  set_names(x) %>%
  list2env(.GlobalEnv)

2 Comments

is there a way to just pass a vector into this code rather than having to type out iris1, iris2, iris3 twice (once for the map function and then once for set_names)? For example to have code earlier on to designate the df's as iris_dfs<-c("iris1","iris2","iris3")
Yes, @Basil, see my edited solution.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.