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.

1
  • 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 applies. Commented Jan 3, 2020 at 20:03

3 Answers 3

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"
Sign up to request clarification or add additional context in comments.

Comments

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)))

2 Comments

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. Updated the post
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"

2 Comments

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?
So in the loop it will be eval(call(paste0("a", i)))

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.