如何在 R 函数中使用 switch 语句?

我想为 R 中的函数使用语句 switch(),以根据函数参数的值触发不同的计算。

例如,在 Matlab 中,你可以通过写来实现这一点

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

我发现这后 Switch ()语句用法-解释如何使用 switch,但对我没有真正的帮助,因为我想执行更复杂的计算(矩阵运算) ,而不是一个简单的 mean

166013 次浏览

Well, switch probably wasn't really meant to work like this, 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 just a simple thing, but here I use a curly-block so that you can stuff whatever code you want in there...

I hope this example helps. You ca use the curly braces to make sure you've got everything enclosed in the switcher changer guy (sorry don't know the technical term but the term that precedes the = sign that changes what happens). I think of switch as a more controlled bunch of if () {} else {} statements.

Each time the switch function is the same but the command we supply 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 a 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")

those various ways of 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"

This is a more general answer to the missing "Select cond1, stmt1, ... else stmtelse" connstruction in R. It's a bit gassy, but it works an resembles the switch statement present in C

while (TRUE) {
if (is.na(val)) {
val <- "NULL"
break
}
if (inherits(val, "POSIXct") || inherits(val, "POSIXt")) {
val <- paste0("#",  format(val, "%Y-%m-%d %H:%M:%S"), "#")
break
}
if (inherits(val, "Date")) {
val <- paste0("#",  format(val, "%Y-%m-%d"), "#")
break
}
if (is.numeric(val)) break
val <- paste0("'", gsub("'", "''", val), "'")
break
}