Switch 语句不适用于数字对象 [英] Switch statement is not working for numerical objects

查看:39
本文介绍了Switch 语句不适用于数字对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是 R 编程的新手.我不知道我们是否可以对数字对象使用 switch 语句.

I am new to R programming. I don't know whether we could use switch statements for numerical objects.

这是我的代码,

myfunction <- function() {
    x <- 10
    switch(x,
        1={
            print("one")
        },
        2={
            print("two")
        },
        3={
            print("three")
        },
        {
            print("default")     #Edited one..
        }
    )
}

我遇到了这个错误,

test.R:4:18: unexpected '='
3:         switch(x,
4:                 1=
                    ^

请帮我解决这个问题.

推荐答案

myfunction <- function(x) {
                       switch(x,
                              print("one"),
                              print("two"),
                              print("three"))}

myfunction(1)
## [1] "one"

<小时>

如评论中所述,此方法不会评估正在输入的值,而是将它们用作索引.因此,它适用于您的情况,但如果要重新排序语句,它将不起作用(请参阅 @Joshs 答案以获得更好的方法).


As mentioned in comments, this method isn't evaluating the values that are being entered, rather uses them as an index. Thus, it works in your case but it won't work if the statements were to be reordered (see @Joshs answer for better approach).

无论哪种方式,我都不认为 switch 是在这种情况下使用的正确函数,因为它主要用于在不同的替代方案之间切换,而在您的情况下,您基本上是在运行一遍又一遍的相同功能.因此,为每个选项添加额外的语句似乎工作量太大(例如,如果您想显示 20 个不同的数字,则必须编写 20 个不同的语句).

Either way, I don't think switch is the right function to use in this case, because it is mainly meant for switching between different alternatives, while in your case, you are basically running the same function over and over. Thus, adding extra a statement for each alternative seems like too much work (if you, for example, wanted to display 20 different numbers, you'll have to write 20 different statements).

相反,您可以尝试使用 english 包,它允许您显示在 ifelse 语句中定义的尽可能多的数字

Instead, you could try the english package which will allow you to display as many numbers as you will define in the ifelse statement

library(english)
myfunction2 <- function(x) {
                 ifelse(x %in% 1:3, 
                        as.character(as.english(x)), 
                        "default")}
myfunction2(1)
## [1] "one"
myfunction2(4)
## [1] "default"

或者,您也可以通过使用 match

Alternatively, you could also avoid using switch (though not necessarily recommended) by using match

myfunction3 <- function(x) {
  df <- data.frame(A = 1:3, B = c("one", "two", "three"), stringsAsFactors = FALSE)
         ifelse(x %in% 1:3, 
          df$B[match(x, df$A)],
          "default")}
myfunction3(1)
## [1] "one"
myfunction3(4)
## [1] "default"

这篇关于Switch 语句不适用于数字对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆