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!") )
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")
Tyler Rinker May 01 '12 at 4:30 2012-05-01 04:30
source share