“Gary1.csv”、“Gary2.csv”、“Gary3.csv”中保存了一個班級學生三個學期的成績
對三個學期中的成績數據進行集成並重新計算綜合成績和排名,並按排名順序排布(學號9位數111304001~11304047)
Gary1.csv中數據
Gary2.csv中數據
Gary3.csv中數據
cbind是根據列進行合並 (要求:所有數據行數相等)
rbind是根據行進行合並 (要求:所有數據列數相同)

#打開工作目錄文件 setwd('D:\\data') list.files() inputfile1=read.csv(file="Gary1.csv",header=TRUE) inputfile2=read.csv(file="Gary2.csv",header=TRUE) inputfile3=read.csv(file="Gary3.csv",header=TRUE) #刪除inputfile1中的綜合成績和排名,刪除inputfile2中的學號、姓名、綜合成績和排名 result=cbind(inputfile1[,-c(10,11)],inputfile2[,-c(1,2,12,13)]) #數據集列合並 #同理 result2=cbind(result,inputfile3[,-c(1,2,7,8)]) #對學生成績進行相加,得到一組數據(我自己測試學生成績是從第三列到第二十二列的) #相加成績保存到evaluation中 evaluation=apply(result2[,3:22], 1,mean,na.rm=TRUE) #apply函數一般有三個參數 #第一個參數代表矩陣對象 #第二個參數代表要操作矩陣的維度 1表示對行進行處理,2表示對列進行處理 #第三個參數就是處理數據的函數 #apply會分別一行或一列處理該矩陣的數據。 #將evaluation用“綜合測評”添加到resule2中,將結果用result11保存 result11=data.frame(result2,'綜合測評'=evaluation) #對result11中按綜合測評成績進行decreasing減少量排名 result22=result11[order(result11$綜合測評,decreasing = TRUE), ] result33=data.frame(result22,'測評排名'=order(result22$綜合測評,decreasing = TRUE)) result33
實現過程
apply函數三個參數:
第一個參數代表矩陣對象
第二個參數代表要操作矩陣的維度 1表示對行進行處理,2表示對列進行處理
第三個參數就是處理數據的函數
讀取文件數據保存到inputfile中
inputfile1=read.csv(file="Gary1.csv",header=TRUE) inputfile2=read.csv(file="Gary2.csv",header=TRUE) inputfile3=read.csv(file="Gary3.csv",header=TRUE)
刪除inputfile1中的綜合成績和排名,刪除inputfile2,inputfuke3中的學號、姓名、綜合成績和排名(合並數據后這些數據多余了)
result=cbind(inputfile1[,-c(10,11)],inputfile2[,-c(1,2,12,13)]) #數據集列合並 result2=cbind(result,inputfile3[,-c(1,2,7,8)])
計算學生成績並將所得結果添加到學生表中
evaluation=apply(result2[,3:22], 1,mean,na.rm=TRUE) #將evaluation用“綜合測評”添加到resule2中,將結果用result11保存 result11=data.frame(result2,'綜合測評'=evaluation) #對result11中按綜合測評成績進行decreasing減少量排名 result22=result11[order(result11$綜合測評,decreasing = TRUE), ] result33=data.frame(result22,'測評排名'=order(result22$綜合測評,decreasing = TRUE)) result33
當R數據中存在NA時,使用對數據的mean()函數時需要注意NA問題
y<-mean(x)
因為x中有NA,所以當對x進行mean操作時,y會被賦值為NA
對學生成績異常值檢測 傳送門
修改上列代碼28行
evaluation=apply(result2[,3:22], 1,mean)
補充:merge()函數 傳送門
merge 連接兩個數據,官方參考文檔語法
merge(x, y, by = intersect(names(x), names(y)), by.x = by, by.y = by, all = FALSE, all.x = all, all.y = all, sort = TRUE, suffixes = c(".x",".y"), incomparables = NULL, ...)
merge()函數是對數據進行交並補運算,三張表進行數據合並時可先合並第一第二張表,再用所合成結果對第三張表進行合成
測試a和aa中值的不同
setwd('D:\\data') list.files() inputfile1=read.csv(file="Gary1.csv",header=TRUE) inputfile2=read.csv(file="Gary2.csv",header=TRUE) inputfile3=read.csv(file="Gary3.csv",header=TRUE) #刪除inputfile1中的綜合成績和排名,刪除inputfile2中的學號、姓名、綜合成績和排名 result=cbind(inputfile1[,-c(10,11)],inputfile2[,-c(1,2,12,13)]) #數據集列合並 #同理 result2=cbind(result,inputfile3[,-c(1,2,7,8)]) a=merge(inputfile1,inputfile2,by=c("學號","課程名稱")) aa=merge(inputfile1,inputfile2,by=c("學號","課程名稱","綜合排名")) b=merge(a,inputfile3,by=c("學號","課程名稱"))
發現aa中存在一個人成績存在多個綜合測評、綜合排名的缺陷,把a也添加到by=c("學號","課程名稱","綜合排名")當中
只要第一個學期和第二個學期綜合排名不一樣時,不顯示合並成功的數據!!!
merge()函數對數據的操作還是挺嚴格的!!!