R語言--數據處理案例(標准化、合並、排序等)


1 數據處理案例

(1)數據輸入

student<-c("John Davis","Angla williams","Bullwink Moose",

           "David Jones","Janice Markhammer","cheryl Cushing",

           "Revenen 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 = F)

解釋:roster是數據框名字,stringsAsFactors = F 設置字符串不拆開,即名字中間可以有空格

2)限定小數位數

options(digits = 2)  #有效數最小保留2

3)成績標准化  scale()

 x<-scale(roster[,2:4])

解釋:標准化之后,讓所有的成績具有可比性

 

4)求平均分

score<-apply(x,1,mean)

解釋:按行求均值:apply() ,參數設置為1

roster<-cbind(roster,score)

解釋:把求出的平均分這一列合並到原來的表roster中,由於不用主鍵,可以直接使用cbind()來合並

 

(5)求分位數

y<-quantile(roster$score,c(0.8,0.6,0.4,0.2))

解釋:求四個分位點,分別在0.80.60.40.2

 

6)按分位數給成績評定等級

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"

解釋:新增加一列grade,根據標准化之后的平均分和四個分位點來划分等級

 

7)拆分first namelast name

 name<-strsplit((roster$student)," ")

解釋:拆分字符串使用strsplit,第一個參數roster$student是要拆分的對象,第二個參數(空格“ ”)是指定按照什么來拆分

 

(8)把拆分后的名字放回數據集  

firstname<-sapply(name, "[",1)  #提取第一個對象

lastname<-sapply(name, "[",2)  #提取第二個對象

解釋:拆分之后生成的是一個列表,可以使用函數sapply來提取拆分后的名字,[” 表示要提取一個對象(元素),1代表提取第一個對象

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

解釋:cbind()是合並對象的,roster[,-1]意思是保留行並且刪掉第1列(負號代表去除)

 

(9)lastname排序

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

解釋:order()排序函數,order(lastname,firstname)先按lastname,再按firstname排序, 逗號前面是按行排行排序,逗號后面是按列(因為姓氏和名不能拆開,所以按行排序)

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM