R語言資料的排序和合並--ordered();rbind()
阿新 • • 發佈:2019-01-07
R語言資料的排序和合並
leadership借用前一章的:
> leadership managerID testDate country gender age item1 item2 item3 item4 item5 1 1 10/14/08 us M 32 5 4 5 5 5 2 2 10/28/08 us F 45 3 5 2 5 5 3 3 10/1/18 uk F 25 3 5 5 5 2 4 4 10/12/08 uk M 39 3 3 4 NA NA 5 5 5/1/09 uk F 99 2 2 1 2 1 >#按照年齡來排序(升序) >#有缺失值的一定是放在最後面 > newData<-leadership[order(leadership$age),] > newData managerID testDate country gender age item1 item2 item3 item4 item5 3 3 10/1/18 uk F 25 3 5 5 5 2 1 1 10/14/08 us M 32 5 4 5 5 5 4 4 10/12/08 uk M 39 3 3 4 NA NA 2 2 10/28/08 us F 45 3 5 2 5 5 5 5 5/1/09 uk F 99 2 2 1 2 1 > leadership$age[leadership$age==99]<-NA > leadership managerID testDate country gender age item1 item2 item3 item4 item5 1 1 10/14/08 us M 32 5 4 5 5 5 2 2 10/28/08 us F 45 3 5 2 5 5 3 3 10/1/18 uk F 25 3 5 5 5 2 4 4 10/12/08 uk M 39 3 3 4 NA NA 5 5 5/1/09 uk F NA 2 2 1 2 1 > newData<-leadership[order(leadership$age),] > newData managerID testDate country gender age item1 item2 item3 item4 item5 3 3 10/1/18 uk F 25 3 5 5 5 2 1 1 10/14/08 us M 32 5 4 5 5 5 4 4 10/12/08 uk M 39 3 3 4 NA NA 2 2 10/28/08 us F 45 3 5 2 5 5 5 5 5/1/09 uk F NA 2 2 1 2 1 >#按照性別和年齡進行排序,因為性別寫在前面所以先安性別排序,之後性別相同的按年齡在排序 > newData<-leadership[order(gender,age),] > newData managerID testDate country gender age item1 item2 item3 item4 item5 3 3 10/1/18 uk F 25 3 5 5 5 2 2 2 10/28/08 us F 45 3 5 2 5 5 5 5 5/1/09 uk F NA 2 2 1 2 1 1 1 10/14/08 us M 32 5 4 5 5 5 4 4 10/12/08 uk M 39 3 3 4 NA NA > #對性別按升序排列,按年齡降序排列 > newData<-leadership[order(gender,-age),] > newData managerID testDate country gender age item1 item2 item3 item4 item5 5 5 5/1/09 uk F NA 2 2 1 2 1 2 2 10/28/08 us F 45 3 5 2 5 5 3 3 10/1/18 uk F 25 3 5 5 5 2 4 4 10/12/08 uk M 39 3 3 4 NA NA 1 1 10/14/08 us M 32 5 4 5 5 5
資料集的合併
合併函式是rbind()函式
例:兩個資料框的合併例項
#先讀入資料 > stamp1Z<-"C:\\Users\\Administrator\\Desktop\\test1.csv" > stamp1<-read.csv(stamp1Z,sep = ",") > stamp1 編號 姓名 年齡 1 1 anne 12 2 2 qiqi 14 3 3 jiajia 16 4 4 nana 23 5 5 maomao 21 6 6 lima 22 7 7 mama 34 > stamp2Z<-"C:\\Users\\Administrator\\Desktop\\test2.csv" > stamp2<-read.csv(stamp2Z,sep = ",") > stamp2 編號 姓名 年齡 1 11 anne 12 2 12 qiqi 14 3 13 jiajia 16 4 14 nana 23 5 15 maomao 21 6 16 lima 22 7 17 mama 34 > stampz<-rbind(stamp1,stamp2) #用rbind()將stamp1和stamp2繫結在一起 > stampz 編號 姓名 年齡 1 1 anne 12 2 2 qiqi 14 3 3 jiajia 16 4 4 nana 23 5 5 maomao 21 6 6 lima 22 7 7 mama 34 8 11 anne 12 9 12 qiqi 14 10 13 jiajia 16 11 14 nana 23 12 15 maomao 21 13 16 lima 22 14 17 mama 34