r intro 20140716-basic

48
R 統計軟體簡介(1) 環境簡介、運算、變數、套件 徐峻賢 中央研究院語言學研究所 大腦與語言實驗室

Upload: kevin-chun-hsien-hsu

Post on 16-Jul-2015

41 views

Category:

Data & Analytics


1 download

TRANSCRIPT

Page 1: R intro 20140716-basic

R 統計軟體簡介(1)

環境簡介、運算、變數、套件

徐峻賢

中央研究院語言學研究所

大腦與語言實驗室

Page 2: R intro 20140716-basic

R 統計軟體發展歷史

• R 統計軟體最初是由Ross Ihaka及Robert Gentleman兩人以統計分析及繪圖為目的,仿S語言的架構為基礎而發展出來的統計軟體,可視為改進版本的S語言。大部分的S語言程式碼可直接或稍做修改後就在R上面執行

• R屬於GNU計畫中的一個項目,目前是由R Development Core Team維護及發展

• 目前R最新的版本為3.1.1版(2014.07.10)

Page 3: R intro 20140716-basic

=

wizard“R” 使用者就像巫師,他們使用統計學家研發的咒語,或者自行開發的指令。R使用者不用付錢請統計學家工作,而且累積足夠的經驗之後,使用者會釋放無限的力量,改變統計分析的環境 (就像鄧布利多那樣)。

Page 4: R intro 20140716-basic

R的特色及功能

• 有效的資料處理及存取能力

• 方便的矩陣操作與運算能力

• 簡單且發展完善的程式語言環境(S 語言)– open source, 開放原始碼

• 活躍的咨詢社群

• 強迫使用者理解統計分析的步驟

•免費

Page 5: R intro 20140716-basic

R的缺點

• 沒有圖形化界面

• 需要較長的學習時間

• 沒有公司/企業支援(不能客訴),使用者必須自行克服問題(容易有挫折感)

• 常常在不知不覺中犯錯

–要反覆檢查指令、輸出結果

• help 訊息幫助不大

Page 6: R intro 20140716-basic

軟體下載

• Google 搜尋 “R” 第一個顯示即是R統計軟體網頁

• The R Project for Statistical Computing

• CRAN

• 選擇下載點:http://cran.csie.ntu.edu.tw/

• Windows baseR-3.0.0-win32.exe

Page 7: R intro 20140716-basic

• R 的主要操作界面

• 兩種視窗:

– Document (scripts)

– Console

Page 8: R intro 20140716-basic

• 互動式界面

撰寫一些指令,然後執行

Page 9: R intro 20140716-basic

在這邊取得輸出 (結果),檢查是否符合預期

撰寫一些指令,然後執行

• 互動式界面

Page 10: R intro 20140716-basic

修改指令在這邊取得輸出 (結果),檢查是否符合預期

• 互動式界面

Page 11: R intro 20140716-basic
Page 12: R intro 20140716-basic

最後,確認程式無誤並且存入語法檔,將來可以使用

Page 13: R intro 20140716-basic

Seriously, how it works?

Page 14: R intro 20140716-basic

數學運算

> 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

Page 15: R intro 20140716-basic

• Beginner's notes:

> q()

## just quit R

## ctl + alt + esc

> getwd()

> setwd(“C:/”)

> help(function) or > help(library)

> dir()

> ls()

> rm(list = ls())

Page 16: R intro 20140716-basic

R 的學習目標

• 讀入外部資料,直接使用別人寫好的packages/functions

• 讀入外部資料作資料處理/轉換/彙整

• 讀入外部資料,並作資料處理/轉換,再使用現有的packages/functions 計算

• 修改他人所寫的packages/functions,以適用於自己的資料分析任務

• 依照自己的特殊需求寫出全新的程式

Page 17: R intro 20140716-basic

• 「不算」複雜的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)

Page 18: R intro 20140716-basic

複雜 R 程式的可能架構

• 資料處理:

–條件過濾、轉換、新增變數、分割、合併、變數轉碼, etc.

• 使用者自訂函數

• 重新改寫他人的函數或套件

• 自製套件(package)

Page 19: R intro 20140716-basic

如何撰寫 R 程式?

• 和撰寫論文一樣:– 研究動機與文獻探討

• 從R社群找過去的Q&A; 尋找可用的 package

– 方法• 演算程序 (e.g., 公式、參數、ANOVA)

– 材料• 讀取外部資料、自製模擬資料

– 程序• 轉換資料、各種想像不到的細節…

– 結果與結論

Page 20: R intro 20140716-basic

Path of R program (and packages) in Windows system: Program FilesC:\Program Files\R\R-n.n.n\etc\Rprofile.site

Page 21: R intro 20140716-basic

Path of R program (and packages) in Mac: Apps and Frameworks(X11 or terminal) ~/.Rprofile

Page 22: R intro 20140716-basic

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?

Page 23: R intro 20140716-basic

套 件

install.packages() 自動下載與安裝指定的套件,例如要安裝lme4套件:

>install.packages(”lme4")

> install.packages(”lme4", repos = "http://cran.csie.ntu.edu.tw")

更新 R 的套件:

> update.packages()

查看目前環境中已經安裝的套件:

> library()

Page 24: R intro 20140716-basic

套 件

尋找可安裝的套件可使用:

> available.packages()

載入指定的套件:

> library(lme4)

查看指定套件的相關資訊可使用 help 參數,例如:

> library(help = lme4)

Page 25: R intro 20140716-basic
Page 26: R intro 20140716-basic
Page 27: R intro 20140716-basic

變數類型

• R有很多種資料形式。較常使用的有:vectors, matrices, lists, and data frames

• 列出記憶體裡面暫存的資料:

> ls()

• 辨別資料類型的指令:

> str()

> class()

Page 28: R intro 20140716-basic

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)

Page 29: R intro 20140716-basic

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

Page 30: R intro 20140716-basic

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

Page 31: R intro 20140716-basic

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

Page 32: R intro 20140716-basic

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

Page 33: R intro 20140716-basic

useful commands on vectors

rev(x) # reverses the vectorsum(x) # sums all the elements in a numeric or logical vectorcumsum(x) # returns a vector of cumulative sums (or a running total)diff(x) # returns a vector of differences between adjacent elementsmax(x) # returns the largest elementmin(x) # returns the smallest elementrange(x) # returns a vector of the smallest and largest elementsmean(x) # returns the arithmetic mean

Page 34: R intro 20140716-basic

factors

Page 35: R intro 20140716-basic

colors 和 colors.fc差在哪裡?

Page 36: R intro 20140716-basic

試試看下列的指令有什麼作用?

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)

Page 37: R intro 20140716-basic

matrix

> fix(USPersonalExpenditure)

Page 38: R intro 20140716-basic

matrix

Page 39: R intro 20140716-basic

matrix

• 呼叫特定欄位的資料

USPersonalExpenditure[1, 3]

USPersonalExpenditure["Food and Tobacco", "1950"]

USPersonalExpenditure[1, "1950"]

Page 40: R intro 20140716-basic

matrix

• 呼叫特定欄位的資料

USPersonalExpenditure[1, c(5, 3, 1)]

USPersonalExpenditure["Food and Tobacco", c("1960", "1950", "1940")]

Page 41: R intro 20140716-basic

matrix

apply(matrix, dimension, function, function_arguments)

apply(USPersonalExpenditure, 2, sum)

apply(USPersonalExpenditure, 1, sum)

apply(USPersonalExpenditure, 2, mean)

Page 42: R intro 20140716-basic

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.

Page 43: R intro 20140716-basic

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)

Page 44: R intro 20140716-basic

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)

Page 45: R intro 20140716-basic

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.

Page 46: R intro 20140716-basic

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”

Page 47: R intro 20140716-basic

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)

Page 48: R intro 20140716-basic

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)