user7170429
user7170429

Reputation:

Having name of a function to be changed "i" times and then run in a for loop in R

I have 3 ARGUMENTLESS functions called f1, f2, and, f3. So, simply f1() will run f1 function, f2() will run f2 function and so on.

Question:

I was wondering how I could have a simple for(i in 1:3) loop that runs f1 through f3?

I have tried the following with no succuss:

f1 = function() plot( rnorm(1e2) ); f2 = function() plot( rnorm(1e3) ); 
f3 = function() plot( rnorm(1e4) )


for (i in 1:3) {

 paste("f", i, "()", sep = "")

 Sys.sleep(1)

}

Upvotes: 1

Views: 35

Answers (3)

Sören Pannier
Sören Pannier

Reputation: 69

This should do the trick:

f1 <- function() plot( rnorm(1e2) )
f2 <- function() plot( rnorm(1e3) ) 
f3 <- function() plot( rnorm(1e4) )
for (i in 1:3) {

 get(paste0("f", i))()

 Sys.sleep(1)

}

anyway you could also start by putting all your functions into a list aka:

fun_list <- list(f1 = function() plot( rnorm(1e2) ),
                 f2 = function() plot( rnorm(1e3) ), 
                 f3 = function() plot( rnorm(1e4) ))

and then just loop through the list.

Upvotes: 0

akrun
akrun

Reputation: 887691

We can use get to get the function from the global environment

for (i in 1:3) {
    get(paste("f", i, sep = ""), envir = .GlobalEnv)()
    Sys.sleep(1)
 }

Upvotes: 2

John Paul
John Paul

Reputation: 12684

Use do.call in your for loop:

for (i in 1:3) {

  do.call(paste0("f", i), args=list())

}

do.call takes the name of a function as a character string and a list of arguments, and executes the function.

Upvotes: 2

Related Questions