R-lab:
Data Analysis with R #2
劉正山 副教授
csliu@mail.nsysu.edu.tw 國立中山大學政治學研究所 2011.8.2 中研院計量方法營
課程大綱
一、R的基本認識
二、R的基本操作及套件安裝 三、使用R進行分析的相關套件 四、Rcmdr套件的介紹與使用 五、操作舉例
六、動手實作
請先下載本次上課所需的材料:
http://www2.nsysu.edu.tw/politics/liu
要點補充
建議使用R-commander來下指令及管理程式 檔(R檔)的同時,用R的視窗來處理套件
補充:R的圖形能力
> demo(graphics)
要點提醒
資料檔與變數都是「物件」:
Dataset$Variable
attach() #鎖定資料檔
detach() #解除鎖定資料檔
>install.packages(c("Design","Hmisc","Zelig
","nnet", “MASS”))
nnet套件可用來跑multinomial logit models
MASS套件可用來跑ordinal regression models
復習操作
使用car套件裡prestige這個資料檔來試做:
閱覽資料檔說明文件
2D圖
3D圖
線性迴歸模型(收入模型)
把結果貼到Microsoft Word
試試看:我們使用car套件裡的presitige資料檔來 建構一個線性迴歸模型(收入模型)
使用R進行資料分析的基本觀念
Factors
Dataframes
Lists
用R-commander匯入資料
匯入SPSS資料檔:
1. 資料 -> 匯入資料 -> 匯入SPSS資料集
2. 選擇示範用檔案TEDS2006CB_KAO.sav
3. 為資料檔命名為teds2006_kao
4. 取消「轉換數值標記」的勾(保留數值即可,
不保留數值的文中標籤)
用R-Commander重製變數
資料 -> 管理在作用中資料集裡的變數 -> 將變 數重新編碼
寫法: input = output
點選「說明」文件來看看怎麼編寫(不難寫!)
編碼後別忘了再確認是否無誤
> table(TEDS2006$sex)
> table(TEDS2006$gender)
用R-Commander建構模型
以前用R直接寫程式碼的寫法
> glm( turnout ~ factor(gender, ordered=FALSE)+ factor(age)+
factor(partyID, ordered=FALSE),
family=binomial, data=kao06)
現在用R-Commander的做法:
二元勝算對數模型:
統計量 -> 模型適配 -> 廣義線性模型 (GLM)
診斷模型內部的共線性
模型 -> 數值診斷 -> 變異數膨脹因素
(Variance Inflation Factor, VIF)
或直接使用指令
> vif (mod.1)
收尾之一:
用R-commander匯出資料檔
轉存sav檔為rda格式(推薦):
1. 資料 -> 已載入的資料集 -> 儲存作用中的資料集
2. 以好辨認的、與原本資料不同的檔名來來另存研究用的 資料檔(如teds2006_kao.rda)
註:日後要讀取rda檔案的方式:
資料->載入資料集
也可轉存為一般的資料格式(txt, csv, tab分隔等等):
資料 -> 已載入的資料集 -> 輸出作用中的資料集
收尾之二:
另存程式檔
檔案 -> 另存程式檔
另存結果報表
檔案 -> 另存輸出檔
另存圖片
滑鼠右鍵,存成metafile
自學R
> help.start()
> help.seasrch(“KeyWordsYouLikeToLearn”)
相關資源
R的官方網站
http://www.r-project.org/
R Gallery 酷炫統計圖集
http://addictedtor.free.fr/graphiques/
R 學習筆記
http://sites.google.com/site/rprojectnotes/links
推薦入門參考書目
Fox, J. 2002. An R and S-Plus companion
to applied regression. Sage Publications.
Dalgaard, P. 2002. Introductory Statistics
with R. New York: Springer.
Verzani, J. 2005. Using R for Introductory
Statistics. Chapman & Hall/CRC.
Teetor, P. 2011. R Cookbook. O'Reilly.
推薦進階參考書目
Venables, W. N. & Ripley, B. D. 2002.
Modern Applied Statistics with S. Springer.
Murrell, P. R 2010. R Graphics. Boca Raton, FL : Chapman & Hall/CRC
Horton, N. J. & Kleinman, K. 2010. Using R
for Data Management, Statistical Analysis,
and Graphics. CRC Press
其他可用的(更專業的)程式編輯器
(只是目前都無中文版且不見得更好上手)
Emacs
http://vgoulet.act.ulaval.ca/en/emacs/wi ndows/
WinEdt
http://www.winedt.com/download.html
JGR
http://www.rforge.net/JGR/index.html
謝謝!
歡迎批評指教,多多交流。
對於R-commander的中文翻譯有任何問題或 建議歡迎與劉老師聯絡。