2015-09-27 61 views
3
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"} 
    } 

我要分配相應的等級在表中的列級有進口 當我嘗試此代碼提到了以下錯誤:分配字母等級來testscores在一個表中的R

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

文檔這可以幫助你 http://stackoverflow.com/questions/17685502/in-r-getting-the-following-error-attempt-to-replicate-an-object-of- type-clos – Ars

+0

您正在爲'classlist $ Grade'分配一個函數。爲了你的代碼的工作,你應該首先創建函數myfunc < - function(Testscore){...}'然後應用它'classlist $ Grade < - myfunc(classlist $ Testscore)' – scoa

回答

7

試試這個:R中拇指

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 

好規則:當你有if之類的語句,一個字符串,有幾乎總是一個更好的辦法。閱讀關於cut(...)