链接多个逻辑运算符

时间:2013-02-05 17:26:40

标签: r

我很擅长使用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值是什么,我创建的'program'都会给出相应的最终标记。

我已经尝试了很多方法来做这件事,但R每次都只是错误。我很肯定这是一个编码错误(用户错误),但尽管谷歌搜索;通过参考书进行拖网我无法让它发挥作用。

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

我最近的尝试如下:

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

我一直试图在过去4天内做到这一点 - 所以如果有人能帮助我或指出我正确的方向,我将非常感激!

3 个答案:

答案 0 :(得分:2)

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.
            )
        )
    )

答案 1 :(得分:0)

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

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

答案 2 :(得分:0)

它仅适用于一个ifelse命令:

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