The mget() fuction is a multiple get() function
We use mget() to retrieve multiple objects by their names
I have found this helpful when I want to perform operations on many df (with similar names) without having to type out each name.
For example, I can create four data.frames. They all have similar name patterns. The only difference is the number.
df_1_pr <- data.frame(x = 1:4, y = letters[1:4])
df_2_pr <- data.frame(x = 5:8, y = letters[5:8])
df_3_pr <- data.frame(x = 9:12, y = letters[9:12])
df_4_pr <- data.frame(x = 13:16, y = letters[13:16])
Here is a quick look at the df1 data.frame
x y
1 1 a
2 2 b
3 3 c
4 4 d
We can make a list of the four data.frames using mget()
df_list <- mget(c("df_1_pr", "df_2_pr", "df_3_pr", "df_4_pr))
Or we can alternatively add paste0() and feed in a sequence from 1:4 to write the code more quickly in mget() instead
df_list <- mget(paste0("df_", 1:4, "_pr"))
We can make a function to create a new column to each data frame in the list
df_list <- lapply(df_list, function(df) {
df$x_mult_2 <- df$x * 2
return(df) })
We can look at the fourth data.frame in the list,
df_list[4]
x y x_mult_2
1 13 m 26
2 14 n 28
3 15 o 30
4 16 p 32
Before we combine all the data.frames, we can make an ID variable for each df with the following function:
add_id_variable <- function(df_list) {
for (i in seq_along(df_list)) {
df_list[[i]]$id <- i}
return(df_list)}
Add a year variable
add_year_variable <- function(df_list) {
years <- 2017:2020
for (i in seq_along(df_list)) {
df_list[[i]]$year <- rep(years[i], nrow(df_list[[i]]))}
return(df_list)}
The rep(years[i], nrow(df_list[[i]])) repeats the i-th year from the years vector (years[i]) for nrow(df_list[[i]]) times.
nrow(df_list[[i]]) is the number of rows in the selected data frame.
We can run the function with the df_list
df_list <- add_id_variable(df_list)
Now we can convert the list into a data.frame with the do.call() function in R
all_df_pr <- do.call(rbind, df_list)
do.call() runs a function with a list of arguments we supply.
do.call(fun, args)
For us, we can feed in the rbind() function with all the data.frames in the df_list. It is quicker than writing out all the data.frames names into the rbind() function direction.

