統計分析:R入門與R基礎
R是一個命令驅動的統計軟體包。乍一看,這可能讓人感覺難以使用。但是,有很多理由讓我們學習使用這個程式進行統計分析。其中最重要的兩個原因是
- R是免費的;您可以從 http://www.r-project.org 下載並安裝到幾乎任何型別的計算機上。
- R允許您進行所有可能需要的統計檢驗,從簡單的到高階的都有。這意味著您始終能夠對您的資料進行正確的分析。
R還擁有出色的圖形和程式設計能力,使其成為教學和學習的輔助工具。例如,本書中的所有插圖都是使用R繪製的;透過點選任何插圖,您都可以獲取用於生成它的R命令。
最後一個好處是在您對統計或R有一定的瞭解後,您可以利用R的許多線上資源來幫助您。在本 書的附錄 中列出了相關資源。
本書中的主要文字描述了統計分析的原理和方法,與您使用的統計軟體包無關。但是,在主要文字之外,還包含大量的“R主題”:使用R來闡述特定點的練習和示例。您可能會發現需要一些時間才能適應R,特別是如果您不熟悉計算機語言的概念。
不用擔心!本章和 第二章 中的主題應該可以幫助您入門,讓您能夠理解和使用R的基本功能。本章旨在幫助您入門:安裝R後,您可以學習如何進行 簡單的計算 和 使用函式,如何 儲存結果,如何 獲取幫助,以及如何 退出。第一章中的幾個練習主要展示了使用R時可用的可能性,而第二章則介紹了R使用方面的核心內容:特別是 向量 和 因子,讀取資料 到 資料幀 中,以及 繪製 各種 型別的 圖表。從那時起,練習將更加側重於統計分析。
如果您希望在進行統計討論之前直接完成這些初始練習,您可以 在這裡 檢視它們。請注意,線上完成R主題時,如果您 設定Wikibooks 以更好地顯示R命令,則會更具視覺吸引力。如果R主題妨礙了您閱讀主要文字,您可以點選每個框右上角的箭頭將其隱藏。
如果您尚未在計算機上安裝R,請從 http://www.r-project.org 免費下載最新版本並安裝基本系統。目前您無需安裝任何額外的包。安裝完成後,啟動R,您應該看到類似以下內容
R version 2.11.1 (2010-05-31) Copyright (C) 2010 The R Foundation for Statistical Computing ISBN 3-900051-07-0 R is free software and comes with ABSOLUTELY NO WARRANTY. You are welcome to redistribute it under certain conditions. Type 'license()' or 'licence()' for distribution details. Natural language support but running in an English locale R is a collaborative project with many contributors. Type 'contributors()' for more information and 'citation()' on how to cite R or R packages in publications. Type 'demo()' for some demos, 'help()' for on-line help, or 'help.start()' for an HTML browser interface to help. Type 'q()' to quit R. >
您現在處於R會話中。R是一個命令驅動的程式,那個看起來很可怕的“>”字元意味著R正在等待您輸入內容。不要害怕。您很快就會掌握最簡單的命令,而這對於現在來說已經足夠了。您最終會發現,命令列驅動的介面為您提供了 [1] 在使用更“使用者友好”的軟體包時無法獲得的自由度和功能。
R作為計算器
100+2/3[1] 100.6667
#this is a comment: R will ignore it
(100+2)/3 #You can use round brackets to group operations so that they are carried out first
5*10^2 #The symbol * means multiply, and ^ means "to the power", so this gives 5 times (10 squared), i.e. 500
1/0 #R knows about infinity (and minus infinity)
0/0 #undefined results take the value NaN ("not a number")
(0i-9)^(1/2) #for the mathematically inclined, you can force R to use complex numbers> (100+2)/3 #可以使用圓括號將操作分組,使其先執行 [1] 34 > 5*10^2 #*符號表示乘法,^符號表示“乘方”,因此這是5乘以(10的平方) [1] 500 > 1/0 #R知道無窮大(和負無窮大) [1] Inf > 0/0 #未定義的結果將取NaN值(“非數字”) [1] NaN > (0i-9)^(1/2) #對於數學愛好者,您可以強制R使用複數 [1] 0+3i
- 如果您不瞭解複數,不用擔心:這裡它們並不重要。
- 請注意,您不能使用花括號{}或方括號[]將操作分組在一起
儲存物件
<- 和 -> 來分配名稱,如下面的練習所示。使用哪個符號取決於您是否喜歡將名稱放在前面還是後面(將 -> 視為“放入”,將 <- 視為“設定為”可能會有所幫助)。與許多統計軟體包不同,R 通常不會顯示您執行的分析結果。相反,分析通常會以生成一個可以儲存的物件而結束。然後,您可以隨時從物件中獲取結果。因此,在使用 R 進行統計時,您會經常發現自己需要命名和儲存物件。您選擇的名稱應由字母、數字和“.” 字元組成[3],並且不能以數字開頭。0.001 -> small.num #Store the number 0.0001 under the name "small.num" (i.e. put 0.0001 into small.num)
big.num <- 10 * 100 #You can put the name first if you reverse the arrow (set big.num to 10000).
big.num+small.num+1 #Now you can treat big.num and small.num as numbers, and use them in calculations
my.result <- big.num+small.num+2 #And you can store the result of any calculation
my.result #To look at the stored object, just type its name
pi #There are some named objects that R provides for you> big.num <- 10 * 100 # 如果您反轉箭頭,可以將名稱放在前面(將 big.num 設定為 10000)。 > big.num+small.num+1 # 現在您可以將 big.num 和 small.num 視為數字,並在計算中使用它們 [1] 1001.001 > my.result <- big.num+small.num+2 # 您可以儲存任何計算的結果 > my.result # 要檢視儲存的物件,只需鍵入其名稱 [1] 1002.001 > pi # R 為您提供了一些命名物件 [1] 3.141593
函式
citation()citation() 函式就是一個例子。它可以接受一個可選引數,該引數指定 R 附加包 的名稱。如果您沒有提供可選引數,通常會有一個預設值(對於 citation(),這個預設值是 "base",即提供基本包的引用:提供 R 語言大多數基礎的包)。函式的大多數引數都是命名的。例如,citation 函式的第一個引數名為package。為了提供額外的清晰度,在使用函式時,您可以使用更長的形式name=value 來提供引數。因此
citation("base")
與
citation(package="base")相同。如果一個函式可以接受多個引數,使用長格式還可以更改引數的順序,如下面的示例程式碼所示。
citation("base") #Does the same as citation(), because the default for the first argument is "base"
#Note: quotation marks are needed in this particular case (see discussion below)
citation("datasets") #Find the citation for another package (in this case, the result is very similar)
sqrt(25) #A different function: "sqrt" takes a single argument, returning its square root.
sqrt(25-9) #An argument can contain arithmetic and so forth
sqrt(25-9)+100 #The result of a function can be used as part of a further analysis
max(-10, 0.2, 4.5) #This function returns the maximum value of all its arguments
sqrt(2 * max(-10, 0.2, 4.5)) #You can use results of functions as arguments to other functions
x <- sqrt(2 * max(-10, 0.2, 4.5)) + 100 #... and you can store the results of any of these calculations
x
log(100) #This function returns the logarithm of its first argument
log(2.718282) #By default this is the natural logarithm (base "e")
log(100, base=10) #But you can change the base of the logarithm using the "base" argument
log(100, 10) #This does the same, because "base" is the second argument of the log function
log(base=10, 100) #To have the base as the first argument, you have to use the form name=valuecitation
指的是函式,而
"citation"
是一個文字“字串”。例如,當為繪圖提供標題等時,這很有用。
您可能會發現,瞭解 R 的最棘手方面之一是瞭解在特定情況下使用哪個函式。幸運的是,R 不僅為所有函式提供文件,而且還提供搜尋文件的方法,以及其他獲得幫助的方法。
獲取幫助
help.start() #A web-based set of help pages (try the link to "An Introduction to R")
help(sqrt) #Show details of the "sqrt" and similar functions
?sqrt #A shortcut to do the same thing
example(sqrt) #run the examples on the bottom of the help page for "sqrt"
help.search("maximum") #gives a list of functions involving the word "maximum", but oddly, "max" is not in there!
### The next line is commented out to reduce internet load. To try it, remove the first # sign.
#RSiteSearch("maximum") #search the R web site for anything to do with "maximum". Probably overkill here!which.max()幫助檔案的“另請參閱”部分找到max()函式。不太理想!
退出 R
quit()或其相同的快捷方式q(),它們不需要任何引數。或者,如果你的 R 版本有選單欄,你可以用滑鼠選擇“退出”或“關閉”。q()
在你開始主要文字之前,我們建議你新增一些特定的華夏公益教科書首選項。前三行將以更美觀的格式顯示 R 命令示例。最後一行提供了一個更美觀的格式來顯示由多個繪圖組成的圖形(稱為子圖)。你可以透過建立使用者 CSS 檔案來完成此操作,如下所示。
- 確保你已登入(如果你還沒有帳戶,請建立一個)。
- 訪問你的個人 css 樣式表,位於 Special:MyPage/skin.css。
- 點選“編輯此頁面”。
- 將以下幾行貼上到大型編輯框中
pre {padding:0; border: none; margin:0; line-height: 1.5em; }
.code .input ol {list-style: none; font-size: 1.2em; margin-left: 0;}
.code .input ol li div:before {content: "\003E \0020";}
table.subfigures div.thumbinner, table.subfigures tr td, table.subfigures {border: 0;}- 如果你瞭解任何CSS,請對這個樣式表進行你喜歡的任何更改。
- 最後,透過點選“儲存頁面”來儲存頁面。
夠了!讓我們繼續主要文字。
- ↑ 這些是拙劣的統計笑話嘗試,你很快就會發現。
- ↑ 根據你如何檢視這本書,你可能會在每個命令前面看到一個“>”字元。這不是要輸入的命令的一部分:它是 R 本身產生的,提示你輸入一些內容。如果你從這本書的線上版本複製和貼上,這個字元應該會被自動省略,但如果你正在閱讀紙質版本或 pdf 版本,你應該在輸入 R 時省略“>”提示。
- ↑ 如果你熟悉計算機程式語言,你可能習慣在名稱中使用下劃線(“_”)字元。在 R 中,通常使用“.”來代替它。
- ↑ 你可以使用單引號(')或雙引號(")來分隔文字字串,只要開始和結束引號匹配即可
- ↑ (請注意,這是一個臨時解決方法,直到 GeSHi 支援 R 程式碼,在這種情況下,統計分析:使用 R 入門/R/語法 可以更改。css 程式碼應該真正讀取
.pre {padding:0; border: none; margin:0; line-height: 1.5em; } .source-R ol {list-style: none; font-size: 1.2em; margin-left: 0;} .source_R ol li div:before {content: "\003E \0020";}