首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在R中包含9个else条件的If语句

问在R中包含9个else条件的If语句
EN

Stack Overflow用户
提问于 2012-12-20 20:50:02
回答 3查看 580关注 0票数 6

我有一个函数,它可以查看9种不同的可能性,并相应地选择一个具有以下形式的操作:

我要做的是查找一个向量,对于向量中的每个条目,决定

代码语言:javascript
复制
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

等。

我想用R写这篇文章,我是不是在每一个例子中都写上"else“?

我已经通过以下方式尝试过switch:

代码语言:javascript
复制
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))
}

其中,随机数1到10是使用变量'net‘的函数

switch命令要做的是检查'condition‘的值,如果它是6,如上面的例子所示,则运行函数:random6(net)

EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2012-12-20 20:54:40

使用switch函数,如下所示:

代码语言:javascript
复制
foo <- function(condition){
  switch(condition,
         '1' = print('B'),
         '2' = print('C'),
         '3' = print('D'),
         '4' = print('E'))
}

> foo(1)
[1] "B"
> foo(2)
[1] "C"
> foo(3)
[1] "D"
> foo(4)
[1] "E"

有关详细信息,请访问?switch。

基于您的示例:

代码语言:javascript
复制
condition<-6
FUN<-function(condition){
    switch(condition,
    '1' = random1(net), # Maybe you're missing some commas here
    '2' = random2(net), # and here
    '3' = random3(net), # and here
    '4' = random4(net)
    ....) # all the way to '10' = random10(net)
}

这将会起作用

这对我来说很好用:

代码语言:javascript
复制
Foo <- function(condition){
  x <- 1:20
  switch(condition,
         '1' = mean(x),
         '2' = var(x),
         '3' = sd(x))
}

> Foo(1)
[1] 10.5
> Foo(2)
[1] 35
> Foo(3)
[1] 5.91608
票数 4
EN

Stack Overflow用户

发布于 2012-12-20 22:20:39

这两个答案都为你指出了正确的工具,但这就是我应该如何写东西。到目前为止,OP和两种解决方案都在创建使用全局变量(net)的函数,这不是最佳实践。

假设randomX是一个参数为net的函数,即:

代码语言:javascript
复制
random1 <- function(net){ [...] }
random2 <- function(net){ [...] }
[etc.]

然后你需要做的是:

代码语言:javascript
复制
FUN <- switch(condition,
              '1' = random1,
              '2' = random2,
              [etc.])

或者更好:

代码语言:javascript
复制
FUN.list <- list(random1, random2, [etc.])
FUN <- FUN.list[[condition]]

在这两种情况下,输出都是一个将net作为输入的函数(就像randomX一样),因此您可以通过执行以下操作来评估它:

FUN(net)

还请注意,使用第二种方法,您可以在一小段时间内完成所有操作:

代码语言:javascript
复制
FUN.list[[condition]](net)
票数 6
EN

Stack Overflow用户

发布于 2012-12-20 21:56:25

另一种解决方案是将要调用的所有函数打包到一个列表randoms中,然后根据condition选择一个列表项

代码语言:javascript
复制
randoms <- list(random1, random2, random3, random4, random5, random6, random7, random8, random9, random10)
FUN <- function(condition) {
  randoms[[condition]](net)
}
票数 5
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/13972614

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档