This is probably a basic question, but I was trying to build a function that creates separate data frames in the environment. There is a similar question so I looked here thinking this was the answer, but I am doing something else incorrectly.
I expected this code to create 3 different data frames called "df_result1", "df_result2", "df_result3" in the environment. I thought "df_result1" would be a data frame with "name1" and 2 as values. "df_result2" would be a data frame with a "name2" and 4 as values. Instead, I am only getting items showing up in the values window.
My question is what am I doing wrong--why don't I get 3 data frames in the environment and what do I need to do to get the expected results. Thank you.
Here is my reproducible example
library(tidyverse)
my_numbers <- c(2, 4, 6)
my_names <- c("name1", "name2", "name3")
# make data frame
my_function <- function(name, factor) {
df = data.frame(student = name, number = my_numbers)
}
# lapply function
simple_fx <- function(my_numbers, my_function, my_names) {
i = 1
for(my_name in my_names) {
df <- lapply(my_names, my_function, my_numbers[[i]])
df_merged <- Reduce(function(...) merge(..., all = TRUE), df)
names(df_merged) <- paste0("df_result", i)
list2env(df_merged, envir = .GlobalEnv)
i = i + 1
}
}
simple_fx(my_numbers, my_function, my_names)