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

I want to Print each series in programmatic way using a for loop.

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

Kindly Advise.

3 Answers3

0

to go from a text string to a program in R you have to parse it and then eval it.

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

get makes this nicer:

for (i in 1:3) {
  print(get(paste0("a_", i)))
}
gdkrmr
  • 674
  • 4
  • 16
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
  }

I have used as.name to resolve the variable and eval.parent to get it from environment. Sorry for bothering you guys.

0

If you know you're building several variables of the same kind, put them in a list and use apply functions to do whatever you want:

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"

If you have already a messy workspace, sort it out and do the same:

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"
moodymudskipper
  • 46,417
  • 11
  • 121
  • 167