如何在R中以实际方式引用对象

时间:2017-12-08 11:03:08

标签: r

a_1 <- 1:100;
a_2 <- 10:1000;
a_3 <- 100:10000

我想使用for循环以编程方式打印每个系列。

for (i in 1:3)
{
print(paste("a_", i, sep = "")
}

请告知。

3 个答案:

答案 0 :(得分:0)

从文本字符串转到R中的程序,您必须parse然后eval它。

for (i in 1:3) {
  print(eval(parse(text = paste0("a_", i))))
}

get让这更好:

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

答案 1 :(得分:0)

print_val <- function(id)
{
  print(id)
  #eval.parent(substitute(as.name(paste("a_", id, sep = ""))))
  eval.parent(as.name(paste("a_", id, sep = "")))*2
  }

我使用as.name来解析变量,并使用eval.parent从环境中获取它。很抱歉打扰你们。

答案 2 :(得分:0)

如果您知道自己正在构建多个相同类型的变量,请将它们放入列表中并使用apply函数执行您想要的任何操作:

a_items <- list(11,12,13)                 
a_items <- list(a_1 = 11,a_2 = 12) # define list in one go
a_items <- c(a_items,a_3=13)       # or add some later
a_items[[2]]     # 12
a_items[["a_2"]] # 12
a_items
# $a_1
# [1] 11
# 
# $a2
# [1] 12
# 
# $a_3
# [1] 13
temp <- sapply(names(a_items),function(x) {print(paste("item",x,"has value",a_items[x]))})
# [1] "item a_1 has value 11"
# [1] "item a_2 has value 12"
# [1] "item a_3 has value 13"

如果您已经有一个凌乱的工作空间,请将其排序并执行相同操作:

banana_1 <- 21
banana_2 <- 22
banana_3 <- 23
potatoe_1 <- 31
potatoe_2 <- 32
potatoe_3 <- 33

var_names <- grep("banana",ls(),value = TRUE)
# [1] "banana_1" "banana_2" "banana_3"

bananas <- mget(var_names)
# $banana_1
# [1] 21
# 
# $banana_2
# [1] 22
# 
# $banana_3
# [1] 23

#optionally remove the objects so they don't clutter your workspace
rm(list=var_names)

temp <- sapply(names(bananas),function(x) {print(paste("item",x,"has value",bananas[x]))})
# [1] "item banana_1 has value 21"
# [1] "item banana_2 has value 22"
# [1] "item banana_3 has value 23"