How to use the switch statement in R functions?

I would like to use the switch() operator for my function in R to start various calculations according to the value of the function argument.

For example, in Matlab, you can do this by writing

 switch(AA) case '1' ... case '2' ... case '3' ... end 

I found this post - using the switch () operator - this explains how to use the switch , but is not very useful for me, since I want to perform more complex calculations (matrix operations), rather than a simple mean .

+74
r switch-statement
May 01 '12 at 4:19
source share
3 answers

Well, switch probably wasn't really meant to work that way, but you can:

 AA = 'foo' switch(AA, foo={ # case 'foo' here... print('foo') }, bar={ # case 'bar' here... print('bar') }, { print('default') } ) 

... each case is an expression - usually a simple thing, but here I use a curly block so that you can type the code you need there ...

+93
May 01 '12 at 4:27
source share

Hope this example helps. You can use curly braces to make sure that you have everything enclosed in the switch toggle switch (sorry, I donโ€™t know the technical term, but the term that precedes the = sign that changes what happens). I think of switching as a more controlled bunch of if () {} else {} .

Each time the switch function is the same, but the command contains changes.

 do.this <- "T1" switch(do.this, T1={X <- t(mtcars) colSums(mtcars)%*%X }, T2={X <- colMeans(mtcars) outer(X, X) }, stop("Enter something that switches me!") ) ######################################################### do.this <- "T2" switch(do.this, T1={X <- t(mtcars) colSums(mtcars)%*%X }, T2={X <- colMeans(mtcars) outer(X, X) }, stop("Enter something that switches me!") ) ######################################################## do.this <- "T3" switch(do.this, T1={X <- t(mtcars) colSums(mtcars)%*%X }, T2={X <- colMeans(mtcars) outer(X, X) }, stop("Enter something that switches me!") ) 

Here it is inside the function:

 FUN <- function(df, do.this){ switch(do.this, T1={X <- t(df) P <- colSums(df)%*%X }, T2={X <- colMeans(df) P <- outer(X, X) }, stop("Enter something that switches me!") ) return(P) } FUN(mtcars, "T1") FUN(mtcars, "T2") FUN(mtcars, "T3") 
+40
May 01 '12 at 4:30
source share

those different ways to switch ...

 # by index switch(1, "one", "two") ## [1] "one" # by index with complex expressions switch(2, {"one"}, {"two"}) ## [1] "two" # by index with complex named expression switch(1, foo={"one"}, bar={"two"}) ## [1] "one" # by name with complex named expression switch("bar", foo={"one"}, bar={"two"}) ## [1] "two" 
+39
Jul 16 '15 at 9:07
source share



All Articles