【问题标题】:Chaining multiple logical operators [closed]链接多个逻辑运算符 [关闭]
【发布时间】:2013-02-05 17:26:39
【问题描述】:

我对使用 R 非常陌生,并且在以下方面非常挣扎 - 任何帮助都将不胜感激。

我需要从考试和课程作业 (x&y) 中计算总分,并且需要使用 R 中的逻辑运算符根据以下标准进行计算。

If exam mark is >=50 then the final mark is 0.2x * 0.7y
If exam mark is <50 > 70 then the final mark is y+10
If exam mark is <50 <70 then the final mark is R.

我的问题是我需要将以上所有 3 个标准放在 R 中的一个字符串中,这样无论 x 和 y 具有我创建的“程序”的任何值都会给出相应的最终标记。

我已经尝试了很多方法来做到这一点,但 R 每次都会出错。我很肯定这是一个编码错误(用户错误),但尽管谷歌搜索;翻阅参考书,我就是无法使用它。

我认为问题在于我了解逻辑运算符的工作原理 - 但不了解如果逻辑运算符给出 TRUE 以及如何将其放入一个程序中,如何获得最终标记的正确公式

我最近的尝试如下:

finalmark <- ((y>=50) <- (0.2*x+0.8*y)) |((y<=50 & x>70) <- (y+10)) |((y<=50 & x<70) <-    (y))

过去 4 天我一直在努力解决这个问题 - 所以如果有人可以帮助我或指出正确的方向,我将不胜感激!

【问题讨论】:

  • 我建议你以this question 和相关的答案为例来开始
  • 请注意我的编辑,避免在标题中使用“帮助”和“紧急”等字眼,更不用说全部大写了。
  • 如果y &lt; 50x == 70 会发生什么?

标签: r


【解决方案1】:
finalmark <- 
    # test if a condition is true..
    ifelse( 
        # here's the condition..
        y >= 50 , 
        # ..and if it is, set `finalmark` equal to this.
        0.2 * x * 0.7 * y , 
        # ..otherwise, if the condition is false..
        ifelse( 
            # test out this nested condition..
            y < 50 & x > 70 ,
            # and if THAT is true, set `finalmark` equal to this
            y + 10 ,
            # ..otherwise, if the second condition is also false..
            ifelse( 
                # test if this second nested condition is true
                y <= 50 & x < 70 ,
                # and if THAT is true, set `finalmark` equal to this
                y ,
                # otherwise, set `finalmark` equal to MISSING
                NA

    # close all of your parentheses
    # out to the same level as before.
            )
        )
    )

【讨论】:

    【解决方案2】:

    一行(假设您希望第三个条件输出y,就像您在代码尝试中所做的那样):

    finalmark <- ifelse(y>=50, 0.2*x+0.8*y, ifelse(x>70, y+10, y))
    

    【讨论】:

    • 您好,谢谢您的回答。这适用于我是否可以使用 ifelse 但问题的标准要求提供不使用 ifelse 的解决方案。你对如何做到这一点有什么建议吗?这就是我遇到问题的地方
    • 没有一些示例数据和输出,我无法判断问题所在。
    【解决方案3】:

    它只适用于一个ifelse 命令:

    finalmark <- ifelse(y >= 50, 0.2 * x + 0.8 * y, y + 10 * (x > 70))
    

    【讨论】:

      猜你喜欢
      • 2021-08-16
      • 1970-01-01
      • 2020-04-14
      • 2014-03-18
      • 2023-03-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-02-25
      相关资源
      最近更新 更多