问题
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:
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"
回答2:
We can use mget and return a list of object values
mget(paste0("a", 1:3))
回答3:
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"
来源:https://stackoverflow.com/questions/59584498/r-call-different-variables-dynamically