2

Example: I have the following parameter table:

df <- data.frame(vn=letters[1:3],values=1:3)

I want an automatic way to realize the following R code:

a <- 1
b <- 2
c <- 3

I know I can do the following to brute force it:

invisible(lapply(1:nrow(df), function(x) assign(df[x,1], df[x,2], envir=.GlobalEnv)))

But I am looking for a more beautiful way to do it.

Leonhardt Guass
  • 773
  • 7
  • 24
  • 2
    And why do you want to do that?? This makes no sense. you can accomplish that by `list2env(as.list(tibble::deframe(df)), .GlobalEnv)` By why?? – Onyambu Sep 15 '22 at 23:07
  • if you dont have `tibble` installed, you could run `list2env(as.list(do.call(setNames, unname(rev(df)))), .GlobalEnv)` – Onyambu Sep 15 '22 at 23:07
  • The reason is that I want to do simulations, and the parameters of the different simulations are from different user feed files. @onyambu Thanks for the awesome solution! – Leonhardt Guass Sep 15 '22 at 23:11
  • 1
    If you are trying to solve the problem by assigning objects to the global environment then you are not doing it correctly. I do not know what you are doing but I am sure you can access each element within the dataframe/matrix/vector/container that you have and use that for simulation. Consider not *polluting* the global environment – Onyambu Sep 15 '22 at 23:13
  • This is a good point, I might want to modify the code to do it the way that you suggested. Thanks! – Leonhardt Guass Sep 15 '22 at 23:17
  • Would you want to post your comments as an answer to this question? So that I can accept it. @onyambu – Leonhardt Guass Sep 16 '22 at 03:55
  • There are alot of questions and answers just like the question you posted. Check for example https://stackoverflow.com/questions/51886899/making-multiple-assignments-to-objects-named-as-strings/51888320#51888320 – Onyambu Sep 16 '22 at 06:34
  • Yoy can consider accepting the answer given already – Onyambu Sep 16 '22 at 06:34

1 Answers1

0

Use mapply when you want to iterate over more than 1 list/vector in parallel:

with(df, mapply(assign, x = vn, value = values, MoreArgs = list(envir = .GlobalEnv)))
Gregor Thomas
  • 136,190
  • 20
  • 167
  • 294