統計分析:使用 R/R/R 基礎知識的入門
| 此頁面或部分是一個未開發的草稿或大綱。 您可以幫助完善作品,也可以在專案室尋求幫助。 |
如果您完成所有這些主題中的練習,您應該能夠相對熟練地使用 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 中進行統計分析時,您經常會發現自己命名和儲存物件。您選擇的名稱應包含字母、數字和“.” 字元[2],並且不能以數字開頭。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() 函式。不太理想!。TRUE 或 FALSE[4])。在本主題中,我們將使用 "datasets" 包提供的一些示例向量,其中包含美國州的資料(參見 ?state)。R 本身就是一個基於向量的程式;事實上,我們之前計算中使用的數字只是被視為具有單個元素的向量。這意味著 R 中的大多數基本函式在作為引數給出向量時將按預期工作,如下所示。state.area #a NUMERIC vector giving the area of US states, in square miles
state.name #a CHARACTER vector (note the quote marks) of state names
sq.km <- state.area*2.59 #Arithmetic works on numeric vectors, e.g. convert sq miles to sq km
sq.km #... the new vector has the calculation applied to each element in turn
sqrt(sq.km) #Many mathematical functions also apply to each element in turn
range(state.area) #But some functions return different length vectors (here, just the max & min).
length(state.area) #and some, like this useful one, just return a single value.[1] 51609 589757 113909 53104 158693 104247 5009 2057 58560 58876 6450 83557 56400
[14] 36291 56290 82264 40395 48523 33215 10577 8257 58216 84068 47716 69686 147138 [27] 77227 110540 9304 7836 121666 49576 52586 70665 41222 69919 96981 45333 1214 [40] 31055 77047 42244 267339 84916 9609 40815 68192 24181 56154 97914 > state.name #一個 CHARACTER 向量(注意引號),包含州名
[1] "Alabama" "Alaska" "Arizona" "Arkansas" [5] "California" "Colorado" "Connecticut" "Delaware" [9] "Florida" "Georgia" "Hawaii" "Idaho"
[13] "Illinois" "Indiana" "Iowa" "Kansas" [17] "Kentucky" "Louisiana" "Maine" "Maryland" [21] "Massachusetts" "Michigan" "Minnesota" "Mississippi" [25] "Missouri" "Montana" "Nebraska" "Nevada" [29] "New Hampshire" "New Jersey" "New Mexico" "New York" [33] "North Carolina" "North Dakota" "Ohio" "Oklahoma" [37] "Oregon" "Pennsylvania" "The smallest state" "South Carolina" [41] "South Dakota" "Tennessee" "Texas" "Utah" [45] "Vermont" "Virginia" "Washington" "West Virginia" [49] "Wisconsin" "Wyoming" > sq.km <- state.area*2.59 #標準算術適用於數值向量,例如將平方英里轉換為平方公里 > sq.km #... 給出另一個向量,其中對每個元素依次執行計算
[1] 133667.31 1527470.63 295024.31 137539.36 411014.87 269999.73 12973.31 5327.63 [9] 151670.40 152488.84 16705.50 216412.63 146076.00 93993.69 145791.10 213063.76
[17] 104623.05 125674.57 86026.85 27394.43 21385.63 150779.44 217736.12 123584.44 [25] 180486.74 381087.42 200017.93 286298.60 24097.36 20295.24 315114.94 128401.84 [33] 136197.74 183022.35 106764.98 181090.21 251180.79 117412.47 3144.26 80432.45 [41] 199551.73 109411.96 692408.01 219932.44 24887.31 105710.85 176617.28 62628.79 [49] 145438.86 253597.26 > sqrt(sq.km) #許多數學函式也依次應用於每個元素
[1] 365.60540 1235.90883 543.16140 370.86299 641.10441 519.61498 113.90044 72.99062 [9] 389.44884 390.49819 129.24976 465.20171 382.19890 306.58390 381.82601 461.58830
[17] 323.45487 354.50609 293.30334 165.51263 146.23826 388.30328 466.62203 351.54579 [25] 424.83731 617.32278 447.23364 535.06878 155.23324 142.46136 561.35100 358.33202 [33] 369.04978 427.81111 326.74911 425.54695 501.17940 342.65503 56.07370 283.60615 [41] 446.71213 330.77479 832.11058 468.96955 157.75712 325.13205 420.25859 250.25745 [49] 381.36447 503.58441 > range(state.area) #但有些函式返回不同長度的向量(這裡,只是最大值和最小值)。 [1] 1214 589757 > length(state.area) #有些函式(如這個有用的函式)只返回一個值。 [1] 50
c(),之所以這樣命名是因為它將concatenates物件連線在一起。但是,如果您想建立由數字的規律序列組成的向量(例如 2、4、6、8、10、12 或 1、1、2、2、1、1、2、2),可以使用幾個替代函式,包括 seq()、rep() 和 : 運算子。c("one", "two", "three", "pi") #Make a character vector
c(1,2,3,pi) #Make a numeric vector
seq(1,3) #Create a sequence of numbers
1:3 #A shortcut for the same thing (but less flexible)
i <- 1:3 #You can store a vector
i
i <- c(i,pi) #To add more elements, you must assign again, e.g. using c()
i
i <- c(i, "text") #A vector cannot contain different data types, so ...
i #... R converts all elements to the same type
i+1 #The numbers are now strings of text: arithmetic is impossible
rep(1, 10) #The "rep" function repeats its first argument
rep(3:1,10) #The first argument can also be a vector
huge.vector <- 0:(10^7) #R can easily cope with very big vectors
#huge.vector #VERY BAD IDEA TO UNCOMMENT THIS, unless you want to print out 10 million numbers
rm(huge.vector) #"rm" removes objects. Deleting huge unused objects is sensible[1] "one" "two" "three" "pi" > c(1,2,3,pi) #建立一個數值向量 [1] 1.000000 2.000000 3.000000 3.141593 > seq(1,3) #建立一個數字序列 [1] 1 2 3 > 1:3 #相同的快捷方式(但靈活性較差) [1] 1 2 3 > i <- 1:3 #您可以儲存一個向量 > i [1] 1 2 3 > i <- c(i,pi) #要新增更多元素,您必須再次賦值,例如使用 c() > i [1] 1.000000 2.000000 3.000000 3.141593 > i <- c(i, "text") #向量不能包含不同型別的資料,因此 ... > i #... R 將所有元素轉換為相同型別 [1] "1" "2" "3" "3.14159265358979" "text" > i+1 #數字現在是文字字串:算術運算不可能 Error in i + 1 : non-numeric argument to binary operator > rep(1, 10) # "rep" 函式重複其第一個引數
[1] 1 1 1 1 1 1 1 1 1 1
> rep(3:1,10) #第一個引數也可以是一個向量
[1] 3 2 1 3 2 1 3 2 1 3 2 1 3 2 1 3 2 1 3 2 1 3 2 1 3 2 1 3 2 1
> huge.vector <- 0:(10^7) #R 可以輕鬆處理非常大的向量 > #huge.vector # 除非您想打印出 1000 萬個數字,否則不要取消此註釋 > rm(huge.vector) #"rm" 刪除物件。刪除未使用的巨大物件是明智之舉
factor() 函式用於建立因子並定義可用水平。預設情況下,水平將從向量中的水平獲取***。實際上,您通常不需要使用 factor(),因為在從檔案讀取資料時,R 預設情況下會將文字轉換為因子(參見 統計分析:使用 R 入門 / R / R / 資料框)。您可能需要使用 as.factor()。在內部,R 將水平儲存為從 1 開始的數字,但並非總是很明顯哪個數字對應哪個水平,通常不需要知道。
ordered=TRUE。state.name # 這 *不是* 一個因子 state.name[1] <- "Any text" # 可以在字元向量中替換文字 state.region[1] <- "Any text" # 但不能在因子中替換文字 state.region[1] <- "South" # 這可以 state.abb # 這不是一個因子,只是一個字元向量
character.vector <- c("Female", "Female", "Male", "Male", "Male", "Female", "Female", "Male", "Male", "Male", "Male", "Male", "Female", "Female" , "Male", "Female", "Female", "Male", "Male", "Male", "Male", "Female", "Female", "Female", "Female", "Male", "Male", "Male", "Female" , "Male", "Female", "Male", "Male", "Male", "Male", "Male", "Female", "Male", "Male", "Male", "Male", "Female", "Female", "Female") #a bit tedious to do all that typing
- 使用程式碼可能更容易,例如,女性為 1,男性為 2
Coded <- factor(c(1, 1, 2, 2, 2, 1, 1, 2, 2, 2, 2, 2, 1, 1, 2, 1, 1, 2, 2, 2, 2, 1, 1, 1, 1, 2, 2, 2, 1, 2, 1, 2, 2, 2, 2, 2, 1, 2, 2, 2, 2, 1, 1, 1)) Gender <- factor(Coded, labels=c("Female", "Male")) # 然後可以將它轉換為命名水平
some.missing <- c(1,NA)
is.na(some.missing)is.na(some.missing) [1] FALSE TRUE
stripchart(state.areas, xlab="Area (sq. miles)") #see method="stack" & method="jitter" for others
boxplot(sqrt(state.area))
hist(sqrt(state.area))
hist(sqrt(state.area), 25)
plot(density(sqrt(state.area))
plot(UKDriverDeaths)
qqnorm()
ecdf(統計分析:使用 R 入門 / R / 資料框 統計分析:使用 R 入門 / R / 獲取資料到 R 統計分析:使用 R 入門 / R / 雙變數圖
- ↑ 根據您檢視本書的方式,您可能在每個命令前面看到一個“>”字元。這不是要輸入的命令的一部分:它是 R 本身產生的,用於提示您輸入內容。如果您從本書的線上版本中複製和貼上,此字元應該自動被省略,但如果您閱讀的是紙質或 pdf 版本,則在鍵入 R 時,您應該省略“>”提示。
- ↑ 如果您熟悉計算機程式語言,您可能習慣在名稱中使用下劃線(“_”)字元。在 R 中,通常使用“.”來代替。
- ↑ 您可以使用單引號(')或雙引號(")來分隔文字字串,只要開始和結束引號匹配即可
- ↑ 這些是 R 中的特殊單詞,不能用作物件的名稱。物件
T和F是TRUE和FALSE的臨時快捷方式,但如果您使用它們,請注意:由於 T 和 F 只是普通的物件名稱,您可以透過覆蓋它們來更改它們的含義。 - ↑ 實際上有 3 種允許的數字型別:“普通”數字、複數和簡單整數。本書幾乎完全處理其中的第一種型別。
- ↑ 這並不完全正確,但除非您是計算機專家,否則您不太可能使用最終型別:儲存“原始”計算機位的元素向量,參見
?raw