Assign multiple objects to .GlobalEnv from within a function
Update of 2018-10-10:
The most succinct way to carry out this specific task is to use list2env()
like so:
## Create an example list of five data.framesdf <- data.frame(x = rnorm(25), g = rep(factor(LETTERS[1:5]), 5))LIST <- split(df, df$g)## Assign them to the global environmentlist2env(LIST, envir = .GlobalEnv)## Check that it workedls()## [1] "A" "B" "C" "D" "df" "E" "LIST"
Original answer, demonstrating use of assign()
You're right that assign()
is the right tool for the job. Its envir
argument gives you precise control over where assignment takes place -- control that is not available with either <-
or <<-
.
So, for example, to assign the value of X
to an object named NAME
in the the global environment, you would do:
assign("NAME", X, envir = .GlobalEnv)
In your case:
df <- data.frame(x = rnorm(25), g = rep(factor(LETTERS[1:5]), 5))LIST <- split(df, df$g)NAMES <- c("V", "W", "X", "Y", "Z")lapply(seq_along(LIST), function(x) { assign(NAMES[x], LIST[[x]], envir=.GlobalEnv) })ls()[1] "df" "LIST" "NAMES" "V" "W" "X" "Y" "Z"
If you have a list of object names and file paths you can also use mapply
:
object_names <- c("df_1", "df_2", "df_3")file_paths <- list.files({path}, pattern = ".csv", full.names = T) mapply(function(df_name, file) assign(df_name, read.csv(file), envir=.GlobalEnv), object_names, file_paths)
- I used
list.files()
to construct a vector of all the .csv files in aspecific directory. But file_paths could be written or constructed in any way. - If the files you want to read in are in the current workingdirectory, then file_paths could be replaced with a character vector offile names.
- In the code above, you need to replace {path} with astring of the desired directory's path.