狠狠撸

狠狠撸Share a Scribd company logo
R 統計軟體簡介(1)
環境簡介、運算、變數、套件
徐峻賢
中央研究院語言學研究所
大腦與語言實驗室
R 統計軟體發展歷史
? R 統計軟體最初是由Ross Ihaka及Robert
Gentleman兩人以統計分析及繪圖為目的,
仿S語言的架構為基礎而發展出來的統計軟
體,可視為改進版本的S語言。大部分的S語
言程式碼可直接或稍做修改後就在R上面執
行
? R屬於GNU計畫中的一個項目,目前是由
R Development Core Team維護及發展
? 目前R最新的版本為3.1.1版(2014.07.10)
=
wizard
“R” 使用者就像巫師,他們使用統計學家研發的咒語,或者自行開發的指令。R使用者不
用付錢請統計學家工作,而且累積足夠的經驗之後,使用者會釋放無限的力量,改變統計
分析的環境 (就像鄧布利多那樣)。
R的特色及功能
? 有效的資料處理及存取能力
? 方便的矩陣操作與運算能力
? 簡單且發展完善的程式語言環境(S 語言)
– open source, 開放原始碼
? 活躍的咨詢社群
? 強迫使用者理解統計分析的步驟
?免費
R的缺點
? 沒有圖形化界面
? 需要較長的學習時間
? 沒有公司/企業支援(不能客訴),使用者必
須自行克服問題(容易有挫折感)
? 常常在不知不覺中犯錯
– 要反覆檢查指令、輸出結果
? help 訊息幫助不大
軟體下載
? Google 搜尋 “R” 第一個顯示即是R統
計軟體網頁
? The R Project for Statistical
Computing
? CRAN
? 選擇下載點
:http://cran.csie.ntu.edu.tw/
? Windows ?base?R-3.0.0-win32.exe
? R 的主要操作界面
? 兩種視窗:
– Document (scripts)
– Console
? 互動式界面
撰寫一些指令,然後執行
在這邊取得輸出 (結果),檢查是否
符合預期
撰寫一些指令,然後執行
? 互動式界面
修改指令
在這邊取得輸出 (結果),檢查是否
符合預期
? 互動式界面
R intro 20140716-basic
最後,確認程式無誤
並且存入語法檔,將
來可以使用
Seriously, how it works?
數學運算
> 3 - 4
[1] -1
> 5 * 6
[1] 30
> 7 / 8
[1] 0.875
> 1 + 2 * 3
[1] 7
> (1 + 2) * 3
[1] 9
> 15 / 4
[1] 3.75
> 15 %% 4
[1] 3
> 2^2
[1] 4
> 2^0.5
[1] 1.414214
> 2^ 4.3
[1] 19.69831
> 2^-0.5
[1] 0.7071068
log(4) # natural log
log10(4) # log in base 10
log(4,10) # same as above
sqrt(9) # square root
abs(3-4) # absolute value
exp(1) # exponential
? Beginner's notes:
> q()
## just quit R
## ctl + alt + esc
> getwd()
> setwd(“C:/”)
> help(function) or > help(library)
> dir()
> ls()
> rm(list = ls())
R 的學習目標
? 讀入外部資料,直接使用別人寫好的
packages/functions
? 讀入外部資料作資料處理/轉換/彙整
? 讀入外部資料,並作資料處理/轉換,再使
用現有的packages/functions 計算
? 修改他人所寫的packages/functions,以適用
於自己的資料分析任務
? 依照自己的特殊需求寫出全新的程式
? 「不算」複雜的R程式:
? 不需資料處理,直接使用他人的套件與函數,
e.g.:
babies=read.txt("c:/mydata/babies/babies.txt",header=TRUE)
mean(babies$bwt);
sd(babies$age);
hist(babies$bwt);
plot(babies$bwt, babies$age)
library(lme4)
lmer.fit1=lmer(bwt ~.,data=babies);
summary(lmer.fit1)
複雜 R 程式的可能架構
? 資料處理:
– 條件過濾、轉換、新增變數、分割、合併、變
數轉碼, etc.
? 使用者自訂函數
? 重新改寫他人的函數或套件
? 自製套件(package)
如何撰寫 R 程式?
? 和撰寫論文一樣:
– 研究動機與文獻探討
? 從R社群找過去的Q&A; 尋找可用的 package
– 方法
? 演算程序 (e.g., 公式、參數、ANOVA)
– 材料
? 讀取外部資料、自製模擬資料
– 程序
? 轉換資料、各種想像不到的細節…
– 結果與結論
Path of R program (and packages) in Windows system: Program Files
C:Program FilesRR-n.n.netcRprofile.site
Path of R program (and packages) in Mac: Apps and Frameworks
(X11 or terminal) ~/.Rprofile
Rprofile (optional)
library(languageR)
library(lme4)
library(ggplot2)
library(R.matlab)
library(MASS)
library(effects)
library(ez)
library(car)
library(sciplot)
setwd("/Users/Kevin/Documents/R_docs")
### google: what's in your .Rprofile?
套 件
install.packages() 自動下載與安裝指定的套件,例如要安裝
lme4套件:
>install.packages(”lme4")
> install.packages(”lme4", repos = "http://cran.csie.ntu.edu.tw")
更新 R 的套件:
> update.packages()
查看目前環境中已經安裝的套件:
> library()
套 件
尋找可安裝的套件可使用:
> available.packages()
載入指定的套件:
> library(lme4)
查看指定套件的相關資訊可使用 help 參數,例如:
> library(help = lme4)
R intro 20140716-basic
R intro 20140716-basic
變數類型
? R有很多種資料形式。較常使用的有:
vectors, matrices, lists, and data frames
? 列出記憶體裡面暫存的資料:
> ls()
? 辨別資料類型的指令:
> str()
> class()
vectors(1)
> a = rnorm(100, mean = 50, sd = 5)
> str(a)
num [1:100] 49.2 48.7 46.1 43.9 44.3 ...
> head(a) ### 列出前面六項
[1] 49.17096 48.71730 46.13608 43.89396 44.28375 43.36800
> tail(a) ### 列出最後六項
[1] 52.86879 50.79304 49.25390 41.76034 44.41400 49.13812
> summary(a)
Min. 1st Qu. Median Mean 3rd Qu. Max.
38.77 46.33 49.00 49.29 52.24 61.16
> fix(a)
vectors(2)
> b = c(1,2,3,4,5,6) #### 使用 c() 建立 vector,包含數字項
> str(b)
num [1:6] 1 2 3 4 5 6
> c = c(“1”,“2”,“3”,“4”,“5”,“6”) #### 使用 c() 建立 vector,由字串構成
> str(c)
chr [1:6] "1" "2" "3" "4" "5" "6"
> summary(b)
Min. 1st Qu. Median Mean 3rd Qu. Max.
1.00 2.25 3.50 3.50 4.75 6.00
> summary(c)
Length Class Mode
6 character character
vectors(3)
> mean(b)
[1] 3.5
> mean(c)
[1] NA
警告訊息:
In mean.default(c) : argument is not numeric or logical: returning NA
> d = as.numeric(c) ### help(as)
> str(d)
num [1:6] 1 2 3 4 5 6
> mean(d)
[1] 3.5
vectors(4)
> colors <- c("red", "orange", "yellow", "green", "blue", "indigo", "violet")
> length(colors) ### 計算 vector 長度
[1] 7
> colors[7] ### 回傳第七項
[1] "violet"
> colors[7] <- "purple" ### 把第七項換成 "purple"
> x = rnorm(10, 0, 1)
> idx = x > 1
> idx ### str(idx)
[1] FALSE FALSE TRUE FALSE FALSE FALSE TRUE FALSE FALSE FALSE
> x.select = x[idx]
> x.select
[1] 1.355631 1.165835
useful commands on vectors
sample(x, 4) # randomly picks four states
sample(x) # randomly permute the entire vector
of state names
sample(x, replace=TRUE) # selection with
replacement
useful commands on vectors
rev(x) # reverses the vector
sum(x) # sums all the elements in a numeric or logical vector
cumsum(x) # returns a vector of cumulative sums (or a
running total)
diff(x) # returns a vector of differences between adjacent
elements
max(x) # returns the largest element
min(x) # returns the smallest element
range(x) # returns a vector of the smallest and largest
elements
mean(x) # returns the arithmetic mean
factors
colors 和 colors.fc 差在哪裡?
試試看下列的指令有什麼作用?
pony.colors <- sample(colors, size=500,
replace=TRUE)
str(pony.colors)
pony.colors.f <- factor(pony.colors)
str(pony.colors.f)
plot(pony.colors.f)
matrix
> fix(USPersonalExpenditure)
matrix
matrix
? 呼叫特定欄位的資料
USPersonalExpenditure[1, 3]
USPersonalExpenditure["Food and Tobacco", "1950"]
USPersonalExpenditure[1, "1950"]
matrix
? 呼叫特定欄位的資料
USPersonalExpenditure[1, c(5, 3, 1)]
USPersonalExpenditure["Food and Tobacco", c("1960",
"1950", "1940")]
matrix
apply(matrix, dimension, function, function_arguments)
apply(USPersonalExpenditure, 2, sum)
apply(USPersonalExpenditure, 1, sum)
apply(USPersonalExpenditure, 2, mean)
list()
? Lists can hold data structures of different
types, and of different sizes.
? Each component in a list can be (optionally,
but commonly) separately named.
list()
? A list of Peter O’Toole
pete <- list("Peter", "O'Toole", 1932, FALSE)
print(pete)
pete <- list(first.name = "Peter", last.name =
"O'Toole", yob = 1932, oscar.winner = FALSE)
print(pete)
list()
m1 <- list(title = "Lawrence of Arabia", year = 1962)
m2 <- list(title = "Stardust", year = 2007)
m3 <- list(title = "Troy", year = 2004)
pete$movies <- list(m1, m2, m3)
pete[["roles"]] <- c("T.E. Lawrence", "King", "Priam")
str(pete)
Data frame
? Data frames are two-dimensional data
structures like matrices, but unlike matrices
can have multiple different data types.
? You can think of a data frame as a list of
vectors, where all the vector lengths are the
same.
Data frame
test1<-read.table("c:/test.csv", header=T, sep=",")
#讀取C:test.csv檔案,有標題,分隔符號為 “,”
test2<-read.csv("c:/test.csv", header=T , col.names=c("M","F"))
#讀取C:test.csv檔案,有標題,將column 1 ,2分別命名為 “M”
及 “F”
Data frame
library(foreign)
x=read.spss("d:/somedir/x4.sav") # not a data.frame
names(mydata)
#"id" "score" "age"
mydata2=data.frame(id=x$id,score=x$score,age=x$age)
library(R.matlab)
dataMat <- readMat("my_matlab_file.mat")
data <-data.frame(dataMat$var)
help(state)
state.db <- data.frame(state.name, state.abb,
state.area, state.center, stringsAsFactors=FALSE)
names(state.db)
names(state.db) <- c("name", "abb", "area",
"long", "lat")
state.db$division <- state.division
plot(area ~ division, data=state.db)
plot(lat ~ long, data=state.db)

More Related Content

R intro 20140716-basic