iteratively assign objects with similar names as function arguments, getting rid of -eval(parse())-

StackOverflow https://stackoverflow.com/questions/23165028

  •  06-07-2023
  •  | 
  •  

Question

Suppose I have:

a_1 <- 2
a_2 <- 5
a_3 <- 7

my.foo <- function (input) {print(input^2)}

My aim is to pass all the objects with a name starting with a_ as my.foo() arguments (hence in the example a_1, a_2 and a_3).

The Following code works as expected:

n <- length(ls(pattern = "a_")) 

for (i in 1:n) {  
    A <- paste("a_",i,sep="")
    my.foo(input=eval(parse(text=A)))
}

My feeling is that this is not really "elegant".. it is like "forcing" R to do what I could do with Stata in a way easier way (through macro variables).

I wonder whether there is a more direct way to address the issue. I tried to put a_1, a_2 and a_3 in a list object and then to use apply functions, but without much success.

Thanks, Stefano

Was it helpful?

Solution

Try one of the following:

my.foo <- function (input) input^2
sapply(ls(pattern = "a_"), function(x) my.foo(get(x)))
# a_1 a_2 a_3 
#   4  25  49 
sapply(list(a_1, a_2, a_3), my.foo)
# [1]  4 25 49

I removed the print from your function because it results in double printing with these examples.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top