Quantcast
Channel: Active questions tagged r - Stack Overflow
Viewing all articles
Browse latest Browse all 201894

Using a list to select function to execute

$
0
0

I am trying to create a list with strings that depending on the value of a variable executes different functions.

This would be the code at this moment:

### Functions to be executed
execute_spain <- function(){

  print(paste0("execute spanish functions " ))
}
execute_portugal <- function(){

  print(paste0("execute portugal functions" ))
}

Then there would be a main where user would select a country

available_countries <- c("SPAIN","PORTUGAL","CHILE","BRAZIL")
country <- "SPAIN"

if(country %in% available_countries){
  print("available")
  if(country =="SPAIN"){
    ejecutar_spain()
  }else if (country =="PORTUGAL"){
    execute_portuguese_functions()
  }
}else{
  print("Error: country selected does not exist ")
}

I would like to do something like:

available_countries <- c("SPAIN","PORTUGAL","CHILE","BRAZIL")
country <- "SPAIN"
function_to_execute <- c()
function_to_execute["SPAIN"] <- execute_spain()
function_to_execute["PORTUGAL"] <- execute_portugal()

if(country %in% available_countries){
  print("available")
  function_to_execute[country]
}else{
  print("Error: country selected does not exist ")
}

Am I bound to use an if with all the options available to select the function to execute?


Viewing all articles
Browse latest Browse all 201894

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>