Sim*_*mon 75 r switch-statement
我想在R语句中使用我的函数switch()
来根据函数参数的值触发不同的计算.
例如,在Matlab中你可以通过写作来做到这一点
switch(AA)
case '1'
...
case '2'
...
case '3'
...
end
Run Code Online (Sandbox Code Playgroud)
我发现这个post- switch()语句用法 - 解释了如何使用switch
,但对我来说并没有真正帮助,因为我想执行更复杂的计算(矩阵运算)而不是简单mean
.
Tom*_*mmy 94
好吧,switch
可能不是真的有意这样的工作,但你可以:
AA = 'foo'
switch(AA,
foo={
# case 'foo' here...
print('foo')
},
bar={
# case 'bar' here...
print('bar')
},
{
print('default')
}
)
Run Code Online (Sandbox Code Playgroud)
...每个案例都是一个表达式 - 通常只是一个简单的事情,但在这里我使用一个卷曲块,这样你就可以填充你想要的任何代码......
Tyl*_*ker 40
我希望这个例子有所帮助.您可以使用花括号来确保切换器更换器中包含所有内容(抱歉不知道技术术语,但在=符号之前的术语会改变发生的情况).我认为switch是一组受控制的if () {} else {}
语句.
每次切换功能相同但我们提供的命令都会发生变化.
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!")
)
Run Code Online (Sandbox Code Playgroud)
这里是一个函数:
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")
Run Code Online (Sandbox Code Playgroud)
pet*_*ner 40
那些不同的转换方式 ......
# 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"
Run Code Online (Sandbox Code Playgroud)