将字母等级分配给R中表格中的测试核心

时间:2015-09-27 05:45:27

标签: r

classlist = read.table("classlist.txt", sep="\t", header=T)
classlist
Testscore <- runif(35,60,100)
classlist$Testscore <- Testscore
classlist
classlist$Grade <- function(Testscore) {
 if(Testscore>=95){
         grade = "A"`enter code here`
         } else if(Testscore>=90 & Testscore<95){
          grade = "A-"
         } else if(Testscore>=85 & Testscore<90){
         grade = "B+"
         } else if(Testscore>=80 & Testscore<85){
         grade = "B"
         } else if(Testscore>=75 & Testscore<80){
         grade = "B-"
         } else {grade = "C"}
     }

我想将相应的等级分配给已导入的表中的列等级 当我尝试此代码时,会提到以下错误:

Error in rep(value, length.out = nrows) : 
  attempt to replicate an object of type 'closure'

1 个答案:

答案 0 :(得分:7)

试试这个:

set.seed(1)    # for reproducible example
classlist        <- data.frame(scores=runif(35,60,100))
classlist$grades <- cut(classlist$scores, 
                        breaks=c(0,seq(75,100,by=5)),
                        labels=c("C","B-","B","B+","A-","A"))
head(classlist,10)
#      scores grades
# 1  70.62035      C
# 2  74.88496      C
# 3  82.91413      B
# 4  96.32831      A
# 5  68.06728      C
# 6  95.93559      A
# 7  97.78701      A
# 8  86.43191     B+
# 9  85.16456     B+
# 10 62.47145      C

R中的经验法则:当你有一串if这样的陈述时,几乎总有一种更好的方法。阅读cut(...)

上的文档