統計分析:使用 R 的入門 / R 基礎
R 是一款命令驅動的統計軟體包。乍一看,這可能會讓它看起來難以使用。然而,有許多理由讓你選擇使用這款計算機程式來學習統計學。其中最重要的兩個原因是
- R 是免費的;你可以從 http://www.r-project.org 下載並將其安裝到幾乎任何你喜歡的計算機上。
- R 允許你進行所有你可能需要的統計測試,從簡單到高度複雜的測試。這意味著你應該始終能夠對你的資料進行正確的分析。
R 的額外優勢在於它具有出色的圖形和程式設計能力,可以作為教學和學習的輔助工具。例如,本書中的所有插圖都是使用 R 製作的;透過點選任何插圖,你可以獲取用於生成它的 R 命令。
最後一個好處是,一旦你掌握了統計學或 R 的一些基本知識,你就能發現網上有許多資源可以幫助 R 使用者。你可以從 本書的附錄 中找到一個列表。
本書中的主要文字描述了統計學背後的原因和方法,這些內容與你使用的任何統計軟體包都息息相關。然而,除了主要文字之外,還有大量“R 主題”:使用 R 來闡明特定觀點的練習和示例。你可能會發現你需要花一些時間才能適應 R,特別是如果你不熟悉計算機語言的概念。
別擔心!本章和 第 2 章 中的主題將幫助你入門,讓你能夠理解和使用 R 的基本功能。本章旨在幫助你入門:一旦你安裝了 R,就有一些主題教你如何執行 簡單的計算 和 使用函式,如何 儲存結果,如何 獲取幫助,以及如何 退出。第 1 章中的一些練習主要展示了使用 R 時可供你使用的可能性,然後第 2 章介紹了 R 使用的基礎知識:特別是 向量 和 因素,讀取資料 到 資料框 中,以及 繪圖 各種 型別。從那時起,練習就變得更加統計化了。
如果你想在進行統計討論之前直接完成這些最初的練習,可以從 這裡 收集這些練習。請注意,在線上完成 R 主題時,如果你 設定華夏公益教科書 來以一種美觀的方式顯示 R 命令,你可能會發現它更具視覺吸引力。如果 R 主題妨礙了你閱讀主要文字,你可以透過點選每個框右上角的箭頭來隱藏它們。
如果你尚未在你的計算機上安裝 R,請從 http://www.r-project.org 免費下載最新版本,並安裝基本系統。你暫時不需要安裝任何額外的包。安裝完成後,啟動它,你應該會看到類似下面的內容
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
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 中,通常使用“.”來代替。
- ↑ 您可以使用單引號(')或雙引號(")來分隔文字字串,只要開始和結束引號匹配即可
- ↑ (請注意,這是一個臨時 hack,直到 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";}