第五章 高级数据管理
1.数据处理难题的一套解决方案
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)
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
2.重复和循环(for和while)
3.条件执行(if-else和ifelse)
4.switch函数
5.自编函数
6.Switch函数在自编函数中的运用
7.整合与重构(转置、融合与重铸)
#安装
install.packages("reshape2")