AnthonyH
AnthonyH

Reputation: 105

R call different variables dynamically

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.

Upvotes: 0

Views: 274

Answers (3)

akrun
akrun

Reputation: 887038

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

Upvotes: 4

Rui Barradas
Rui Barradas

Reputation: 76402

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"

Upvotes: 4

Nareman Darwish
Nareman Darwish

Reputation: 1261

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"

Upvotes: 1

Related Questions