R call different variables dynamically

丶灬走出姿态 提交于 2020-01-06 08:06:43

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!