1

I am aware that this is how we get the global variable names in R:

var <- as.list(.GlobalEnv)    
var_names <- names(var)

Once you get the names, is there a way to call the variables using var_names? For instance, if var_names[1] = "a", I would want to write function(var_name[1]) and have it refer to a.

cderv
  • 6,272
  • 1
  • 21
  • 31
creativename
  • 398
  • 2
  • 15
  • Use `get()` to refer to data by its variable name. Use `assign()` to assign values to variable by its name. For instance, `assign("Peace",1)` makes a variable `Peace` which contains `1`. Then do `get("Peace")` – CPak Jul 17 '17 at 18:30
  • 1
    use `mget` if you want to refer to several object – cderv Jul 17 '17 at 18:31
  • @cderv didn't know that...thanks – CPak Jul 17 '17 at 18:31
  • In your example, there's no need to bother with `get`, just do `var[[var_names[1]]]`. More generally, you should avoid recommendations about `get` and `assign` in most circumstances. In this case, you already have a named list and can refer to the objects by name as needed. – joran Jul 17 '17 at 18:31
  • Thank you all for your input. I should have searched more thoroughly. I didn't think creating a list of global environments would also let us call the variables using that list. @joran, I don't think your solution exists in either of the duplicated posts. Would you want to post that as an answer? – creativename Jul 18 '17 at 16:22

0 Answers0