0

I am having an issue assigning variable objects to a list of data frames. For example,

df1 <- data.frame(a = 1, b = 1:10)
df2 <- data.frame(a = 2, b = 1:10)
df3 <- data.frame(a = 3, b = 1:10)

x <- c("a", "b", "c")
y <- list("df1", "df2", "df3")

My goal is to assign each data frame in the y list to the object in x. I can do it long hand.

a <- y[[1]]

But I have many iterations. I have tried the following without any luck

map2(x, y, function(x, y) x <- y) 

and

map2(x, y, ~assign(x, y))

Appreciate any help!

Phil
  • 7,287
  • 3
  • 36
  • 66

2 Answers2

0

We can unlist the list of object names (unlist(y)), get the values with mget in a list, set the names of the list elements with 'x' vector values and use list2env to create objects in the global env (not recommended though)

list2env(setNames(mget(unlist(y)), x), .GlobalEnv)

If we use map2, then we need to get the value of 'y' and also specify the environment to assign the value

map2(x, y, ~ assign(.x, get(.y), envir = .GlobalEnv))

-output

a
#   a  b
#1  1  1
#2  1  2
#3  1  3
#4  1  4
#5  1  5
#6  1  6
#7  1  7
#8  1  8
#9  1  9
#10 1 10

b
#   a  b
#1  2  1
#2  2  2
#3  2  3
#4  2  4
#5  2  5
#6  2  6
#7  2  7
#8  2  8
#9  2  9
#10 2 10
akrun
  • 874,273
  • 37
  • 540
  • 662
  • Thank you for the help! Why is it not recommended to create the objects in the global environment? – Jake Bernards Oct 26 '20 at 18:39
  • @JakeBernards You could do the same in a `list` and store it, or write back as csv without lots of objects in the global env – akrun Oct 26 '20 at 18:50
0

Unfortunately, the above options didn't work in my case. I ended up adapting the suggestions made by akrun which worked.

names(y) <- x
list2env(y, envir=.GlobalEnv)