0

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)
  • just do: `list2env(split(data.frame(numbers = my_numbers,names = my_names),paste0("df_results",1:3)),.GlobalEnv)` – Onyambu Aug 23 '19 at 23:19

1 Answers1

0

I would not recommend writing objects in global environment from inside the function. You can always return list of dataframes from the function but here is one way to do what OP was attempting.

my_function <- function(name, factor) {
  df = data.frame(student = name, number = factor)
  return(df)
} 

simple_fx <- function(my_numbers, my_names) {
    df  <- Map(my_function, my_numbers, my_names)
    names(df) <- paste0("df_result", seq_along(df))
    list2env(df, envir = .GlobalEnv)
}

simple_fx(my_numbers, my_names)

We now have 3 dataframes df_result1, df_result2 and df_result3 in global environment.

Ronak Shah
  • 377,200
  • 20
  • 156
  • 213