if(lastnote [i] <50){中的错误:需要TRUE / FALSE的缺少值

时间:2019-06-26 15:05:13

标签: r for-loop

我正在尝试学习R。所以我是初学者。我想编写如下代码,但出现问题。如果您能帮助我,我将不胜感激。

这只是我的做法。我一直在读一些有关R的书,并且一直在尝试做某事

class1 <- data.frame(name=c("a1","a2","a3","a4","a5","a6","a7","a8","a9","a10"), 
            surname= c("b1","b2", "b3", "b4", "b5","b6","b7","b8","b9","b10"),
            exam1= c(25,35,55,65,75,35,80,90,100,65),
            exam2 = c(56,65,25,95,78,69,45,23,45,63),
            final= c(65,55,78,93,65,89,89,95,100,75))
lastnote <- (((class1$exam1+class1$exam2)/2)*0.4 + (class1$final*0.6))
lastnote
class1[,"lastnote"] <- lastnote

for (i in lastnote)
if(lastnote[i] < 50) {x= "FF"
} else if(lastnote[i] < 60) {x= "CD"
} else if(lastnote[i] < 65) {x= "CC"
} else if(lastnote[i] < 70) {x= "BC" 
} else if(lastnote[i] < 80) {x= "BB"
} else if(lastnote[i] < 90) {x= "AB"
} else {x= "AA"}
在此示例中,

x是学生的字母数字。 我期望在class1中创建一个名为x或new column的向量 非常感谢您的帮助。

3 个答案:

答案 0 :(得分:0)

您可以在cut R中使用base

class1$letters <- cut(class1$lastnote, breaks = c(0, 50, 60, 65, 70, 80, 90, 100), labels = c("FF", "CD", "CC", "BC", "BB", "AB", "AA"))
class1

输出:

   name surname exam1 exam2 final lastnote letters
1    a1      b1    25    56    65     55.2      CD
2    a2      b2    35    65    55     53.0      CD
3    a3      b3    55    25    78     62.8      CC
4    a4      b4    65    95    93     87.8      AB
5    a5      b5    75    78    65     69.6      BC
6    a6      b6    35    69    89     74.2      BB
7    a7      b7    80    45    89     78.4      BB
8    a8      b8    90    23    95     79.6      BB
9    a9      b9   100    45   100     89.0      AB
10  a10     b10    65    63    75     70.6      BB

答案 1 :(得分:0)

我将利用dplyr包结合case_when函数来做到这一点。

class1 %>% 
    mutate(lastnote =((exam1+exam2)/2)*0.4 + (final*0.6),
           Final_Value = case_when(lastnote < 100 ~ 'AA',
                                   lastnote < 90 ~ 'AB',
                                   lastnote < 80 ~ 'BB',
                                   lastnote < 70 ~ 'BC',
                                   lastnote < 65 ~ 'CC',
                                   lastnote < 60 ~ 'CD',
                                   lastnote < 50 ~ 'FF'))

答案 2 :(得分:0)

只需少量更改即可使用相同的循环条件

xx<-c()
for (i in unique(lastnote)){
  if(i < 50) {x= "FF"
  } else if(i < 60) {x= "CD"
  } else if(i < 65) {x= "CC"
  } else if(i < 70) {x= "BC" 
  } else if(i < 80) {x= "BB"
  } else if(i < 90) {x= "AB"
  } else {x= "AA"}
  xx<- append(xx,x)
}

print (xx)
[1] "CD" "CD" "CC" "AB" "BC" "BB" "BB" "BB" "AB" "BB"