Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

If statement with 9 else conditions in R

Tags:

r

I have a function which looks at 9 different possibilities and chooses an action accordingly having the following form:

What I'm doing is looking up a vector and for each entry in the vector deciding

IF the value in the vector is 1 THEN start function B
IF the value in the vector is 2 THEN start function C
IF the value in the vector is 3 THEN start function D
IF the value in the vector is 4 THEN start function E

etc.

I would like to write this in R. Do I just put "else" for every single case?

I have tried switch in the following way:

condition<-6
FUN<-function(condition){
    switch(condition,
    1 = random1(net)
    2 = random2(net)
    3 = random3(net)
    4 = random4(net)
    5 = random5(net)
    6 = random6(net)
    7 = random7(net)
    8 = random8(net)
    9 = random9(net)
    10= random10(net))
}

Where random 1 to 10 are functions using the variable 'net'

and what the switch command is trying to do is checking the value of 'condition' and if its 6 as in the above example then it runs the function: random6(net)

like image 746
user1723765 Avatar asked Dec 20 '12 12:12

user1723765


2 Answers

Both answers pointed you to the right tools, but this is IMHO how things ought to be written. The OP and both solutions so far are creating functions that use a global variable (net) which is not best practice.

Assuming randomX are functions of one argument net, i.e.:

random1 <- function(net){ [...] }
random2 <- function(net){ [...] }
[etc.]

Then you need to do:

FUN <- switch(condition,
              '1' = random1,
              '2' = random2,
              [etc.])

or better:

FUN.list <- list(random1, random2, [etc.])
FUN <- FUN.list[[condition]]

In both cases, the output is a function that takes net as an input (just like randomX) so you can evaluate it by doing:

FUN(net)

Also note that you can do everything in one short scoop using the second approach:

FUN.list[[condition]](net)
like image 117
flodel Avatar answered Oct 16 '22 01:10

flodel


Another solution is to pack all the functions you want to call into a list randoms and then select a list item based on condition:

randoms <- list(random1, random2, random3, random4, random5, random6, random7, random8, random9, random10)
FUN <- function(condition) {
  randoms[[condition]](net)
}
like image 30
QkuCeHBH Avatar answered Oct 16 '22 03:10

QkuCeHBH