0

I am looking for a way to call different variables dynamically.

Like, if I've got variables a1, a2, and a3 in a for loop, and I want to use a different one each time. Something like:

a1 = "Good Morning"
a2 = "Good Afternoon"
a3 = "Good Night"

for (i in 1:3){
paste("a" & i)
}

That paste line doesn't work, and that's what I'm looking for. A way to combine "a" and i so it reads as the variable a1, then a2, then a3.

AnthonyH
  • 55
  • 6
  • 2
    Use vectors or lists, not sequentially named variables. You don't have data frames, but my answer at [How to make a list of data frames](https://stackoverflow.com/a/24376207/903061) applies. – Gregor Thomas Jan 03 '20 at 20:03

3 Answers3

4

We can use mget and return a list of object values

mget(paste0("a", 1:3))

If we want to apply three different functions, use Map/mapply

Map(function(f1, x) f1(x), list(fun1, fun2, fun3),  mget(paste0("a", 1:3)))
akrun
  • 674,427
  • 24
  • 381
  • 486
  • Awesome, thanks. Do you also happen to know of a way to do this with functions? Like, say a1, a2, and a3 were three different functions? How could I do this in that case? – AnthonyH Jan 10 '20 at 19:46
  • @AnthonyH. Updated the post – akrun Jan 10 '20 at 19:48
4

Yet another answer with mget, but determining the "a" variables that exist in the .GlobalEnv with ls().

a_vars <- ls(pattern = "^a")
mget(a_vars)
#$a1
#[1] "Good Morning"
#
#$a2
#[1] "Good Afternoon"
#
#$a3
#[1] "Good Night"
Rui Barradas
  • 44,483
  • 8
  • 22
  • 48
1

You can use get() to evaluate it as follows;

a1 = "Good Morning"
a2 = "Good Afternoon"
a3 = "Good Night"

for (i in 1:3){
  print(get(paste0("a",  i)))
}

# [1] "Good Morning"
# [1] "Good Afternoon"
# [1] "Good Night"
Nareman Darwish
  • 1,161
  • 4
  • 14