一个R语言使用函数处理的基本的案例

来源:互联网 发布:淘宝天下网商 编辑:程序博客网 时间:2024/05/16 12:08

要求:对这个表的处理


options(digits=2)


Student <- c("John Davis", "Angela Williams", 
    "Bullwinkle Moose", "David Jones", 
    "Janice Markhammer", "Cheryl Cushing",
    "Reuven Ytzrhak", "Greg Knox", "Joel England",
    "Mary Rayburn")
Math <- c(502, 600, 412, 358, 495, 512, 410, 625, 573, 522)
Science <- c(95, 99, 80, 82, 75, 85, 80, 95, 89, 86)
English <- c(25, 22, 18, 15, 20, 28, 15, 30, 27, 18)
roster <- data.frame(Student, Math, Science, English,
    stringsAsFactors=FALSE)
    
z <- scale(roster[,2:4]) 
score <- apply(z, 1, mean)                                            
roster <- cbind(roster, score)


y <- quantile(score, c(.8,.6,.4,.2))                                   
roster$grade[score >= y[1]] <- "A"                                     
roster$grade[score < y[1] & score >= y[2]] <- "B"
roster$grade[score < y[2] & score >= y[3]] <- "C"
roster$grade[score < y[3] & score >= y[4]] <- "D"
roster$grade[score < y[4]] <- "F"


name <- strsplit((roster$Student), " ")                                
lastname <- sapply(name, "[", 2)
firstname <- sapply(name, "[", 1)


roster <- cbind(firstname,lastname, roster[,-1])
roster <- roster[order(lastname,firstname),]


roster

   firstname   lastname Math Science English score grade
6      Cheryl    Cushing  512      85      28  0.35     C
1        John      Davis  502      95      25  0.56     B
9        Joel    England  573      89      27  0.70     B
4       David      Jones  358      82      15 -1.16     F
8        Greg       Knox  625      95      30  1.34     A
5      Janice Markhammer  495      75      20 -0.63     D
3  Bullwinkle      Moose  412      80      18 -0.86     D
10       Mary    Rayburn  522      86      18 -0.18     C
2      Angela   Williams  600      99      22  0.92     A
7      Reuven    Ytzrhak  410      80      15 -1.05     F

0 0
原创粉丝点击