1부 r프로그램 tutorial

21

Post on 08-Nov-2014

62 views

Category:

Documents


6 download

DESCRIPTION

tutorial

TRANSCRIPT

Page 1: 1부 R프로그램 Tutorial
Page 2: 1부 R프로그램 Tutorial

1

R Tutorial

R

Page 3: 1부 R프로그램 Tutorial

1

R 사용법 특강

이화여자 대학교통계학과 송종우

1. R 기초

Page 4: 1부 R프로그램 Tutorial

2

R : 인터넷에서 자유롭게 다운받아 사용할 수 있는 통계시스템

1 R의 소개

R은 프로그램의 기능을 가지고 있어 자체로서도 유용한

기능들을 구현할 수 있을 뿐만 아니라 자료 처리 및

그래픽스 분야에 탁월한 기능을 가지고 있음

http://www.r-project.org

프로그램 및 매뉴얼 등을 무료로 다운

R 사이트

2 R의 기능

자료처리기능

자료의 구성, 소팅, 결합 등이 프로그램 처리로 쉽게 이루어짐

자료분석 기능기능

자료를 분석하기 위해 필요한 수치적 계산 및 분석 결과

제공 등이 다양

언어기능

자 대화형으로 프로그래밍언어로서 함수문을 쉽게 작성할

수 있으며 C언어 및 FORTRAN 언어 등과 인터페이스수 있으며, C언어 및 FORTRAN 언어 등과 인터페이스

(Interface)가 가능

그래픽스

대화형 그래픽스에 의한 자료분석의 기능 및 분석결과의

그래픽스 처리 기능이 뛰어남

Page 5: 1부 R프로그램 Tutorial

3

3 R 다운받기

R 사이트(www.r-project.org)

R 사이트 초기 화면에서 왼편 창의 CRAN을 선택

3 R 다운받기

Mirror 사이트 선택

R 다운받기 위한 Mirror사이트 선택

Page 6: 1부 R프로그램 Tutorial

4

3 R 다운받기

OS 선택

OS(Linux 또는 Window) 선택

3 R 다운받기

base 선택

base 선택

Page 7: 1부 R프로그램 Tutorial

5

3 R 다운받기

Download R 선택

Download R

3 R 다운받기

R Contributors

Page 8: 1부 R프로그램 Tutorial

6

3 R 다운받기

R mannuals

3 R 다운받기

R Books

Page 9: 1부 R프로그램 Tutorial

7

R object1

4 R 프로그래밍

Object type

Vector (numeric, character, logical, complex)

한 vector가 여러가지 type을 가질 수는 없음. x<-c(1,”oh”,5+3i) : type coercion.

Factor

g<-c(‘f’,’f’,’f’,’m’,’m’,’f’); g<-factor(g)

bl f i 아주 유용함 일반 에서 사용가능table function 아주 유용함. 일반 vector에서 사용가능

Vectorization2

4 R 프로그래밍

R의 거의 모든 function들이 vector-in, vector-out 임.

x<-c(1,3,5)

sqrt(x)

vector끼리의 사칙연산 : 기본적으로 요소끼리의 연산임.

Vector와 scalar의 연산 : recycling rule 적용 Vector와 scalar의 연산 : recycling rule 적용.

Page 10: 1부 R프로그램 Tutorial

8

Indexing3

4 R 프로그래밍

R의 가장 powerful한 기능 중 하나.R의 가장 powerful한 기능 중 하나.

x<-c(1,3,5,15,3,2)

x[1], x[1:2], x[c(1,5)], x[x>3], x[x>3 & x<10], x[x<=2 | x>10]

Random number generator4

4 R 프로그래밍

Sequence generator : seq(), rep()

Random numbers from normal t gamma uniform distributionsRandom numbers from normal, t, gamma, uniform distributions

rnorm(), rt(), rgamma(), runif()

Monte Carlo simulation

X ~F, E(h(X)) ?

x_1, …, x_n iid from F : sum(h(x_i))/n converges to E(h(x)) as n goes to infinity

by SLLN.

Example ) x ~ N(3,10), y = (x^2 + 3*x^3 +2)/sqrt(abs(x)+2*x^2), E(y)? P(y<c) ?

Or numerical integration for expectation? Integrate() function.

Page 11: 1부 R프로그램 Tutorial

9

Matrix and Array5

4 R 프로그래밍

x<-matrix(1:20 nrow=4)x< matrix(1:20,nrow=4)

x<-array(1:20,dim=c(2,2,5))

Vector와 마찬가지로 indexing 기능 사용 가능

x[,1], x[,1:2], x[-1,], x[1:3,] x[x[,2]>5,]

행렬연산5

4 R 프로그래밍

행렬연산에 자주 이용되는 함수

ncol(x) 열의 수의 수

nrow(x) 행의 수

t(x) 전치행렬

cbind(...) 열을 더할 때 이용되는 함수

rbind(...) 행을 더할 때 이용되는 함수

diag(x) 대각행렬

apply(x,m,fun) 행 또는 열에 함수 적용

x %*% y 두 행렬의 곱x %*% y 두 행렬의 곱

solve(x) 역행렬

svd(x) Singular Value Decomposition

qr(x) qr Decomposition

eigen(x) eigenvalues(고유값)

chol(x) Choleski decomposition

Page 12: 1부 R프로그램 Tutorial

10

4 R 프로그래밍

List and Dataframe6

4 R 프로그래밍

List object : 여러 가지 attributes(components)를 가질 수 있음. 각각의 attributes

의 type이 달라도 무방함.

mylist<-list(id=1001, name=”Song”, score=c(89,90,95,98))

mylist$id, mylist$score

Dataframe : Data analysis를 수행할 때 가장 많이 사용하게 되는 object. List

object의 special type으로 직사각형의 모양을 가짐. nxp matrix같이 생겼으나j 의 p yp 직사각형의 양을 가짐 p 같이 생겼 나

matrix와의 차이점은 각각의 column이 다른 type을 가질 수 있음.

Workspace and data I/O7

4 R 프로그래밍

R에서는 모든 object를 .RData file에 저장함. 수행했던 command들은 .Rhistory

에 저장함 여러 개의 j t를 수행할 시에는 각 j t별로 폴더를 만들어 놓에 저장함. 여러 개의 project를 수행할 시에는 각 project별로 폴더를 만들어 놓

고 R의 바로가기 시작위치를 그 폴더로 지정해 놓으면 project별로 관리가 가능

함.

Data file을 R로 loading하는 법 : read.table(“filename”, header=T, sep=”,”)

R object를 file로 writing하는 법 : write.table(object, “filename”)

Example) Excel에서 작은 dataframe을 만든 후에 R로 loading하기.

엑셀에서 CSV 파일타입으로 저장할 것.

Page 13: 1부 R프로그램 Tutorial

11

User-defined functions8

4 R 프로그래밍

내가 수행하고자 하는 일을 built-in function을 사용해서 할 수 있는 지를 먼저

체크하자 Built-in function이 user-defined function보다 훨씬 빠르다 하지만 어체크하자. Built in function이 user defined function보다 훨씬 빠르다. 하지만 어

떤 경우에는 스스로 function을 정의해서 사용해야 하는 경우가 있음.

mysum <-function(a,b){res<-a+breturn(res)

}L f ( i i 1 100) { } hil ( diti ) { }• Loop : for ( i in 1:100) { } , while (condition) { }

• If ( condition1){ action1} elseIf (condition2) {action 2} else{action 3}

Built-in functions8

4 R 프로그래밍

Basic functionssum(x),max(x),min(x),which.max(x),which.min(x)range(x) length(x) mean(x) median(x) sd(x) var(x) quantile(x) scale(x)range(x),length(x),mean(x),median(x),sd(x),var(x),quantile(x),scale(x) Vector and mathematical functions

sort(x),rev(x),rank(x),log(x,base),exp(x),sqrt(x),abs(x),round(x,n)

cumsum(x),cumprod(x)

match(x,s),union(x,y),intersect(x,y),setdiff(x,y),is.element(x,y)

choose(n,k), sample(10)

Page 14: 1부 R프로그램 Tutorial

12

5 R 패키지

모든 R 함수와 다양한 데이터셑들은 패키지(package)로 제공됨

예) 군집분석 패키지 “cluster”를 설치하는 방법

① [패키지] - [package 인스톨]을 선택 또는> install.packages(“cluster”)

5 R 패키지

② Cran Mirror 선택 ③ 패키지 cluster 선택

Page 15: 1부 R프로그램 Tutorial

13

5 R 패키지

④ library(cluster) 입력

2. R Graphics

Page 16: 1부 R프로그램 Tutorial

14

1 R Graphics

Bar and Pie chart1

install.packages('vcd')

library(vcd)

counts <- table(Arthritis$Improved)

barplot(counts, main="Simple Bar Plot", xlab="Improvement", ylab="Frequency")

?barplot

counts <- table(Arthritis$Improved, Arthritis$Treatment)

barplot(counts, main="Stacked Bar Plot", xlab="Treatment", ylab="Frequency",

col=c("red", "yellow","green"), legend=rownames(counts)) #check beside option

1 R Graphics

Bar and Pie chart1

par(mfrow=c(2, 2))slices <- c(15, 12,4, 16, 8)

USUK

Simple Pie Chart

US 27%UK 22%

Pie Chart with Percentages

lbls <- c("US", "UK", "Australia", "Germany", "France") pie( slices, labels = lbls,main="Simple Pie Chart")

pct <- round(slices/sum(slices)*100)lbls2 <- paste(lbls, " ", pct, "%", sep="")pie(slices, labels=lbls2, col=rainbow(length(lbls2)), main="Pie Chart with Percentages")

install.packages('plotrix')library(plotrix)i 3 li l b l lbl l d 0 1

Australia

Germany

France

Australia 7%

Germany 29%

France 15%

3D Pie Chart

South16

Pie Chart from a Table (with sample sizes)

pie3D(slices, labels=lbls,explode=0.1,main="3D Pie Chart ")

mytable <- table(state.region)lbls3 <- paste(names(mytable), "\n", mytable, sep="") pie(mytable, labels = lbls3,main="Pie Chart from a Table\n (with sample sizes)")

USUK

Australia

GermanyFrance

Northeast9

16

North Central12

West13

Page 17: 1부 R프로그램 Tutorial

15

1 R Graphics

Histogram and Boxplot2

Histogram Boxplot

한변수의 분포를 보내는 유용.

x<-rnorm(100,0,3)hist(x,prob=T)lines(density(x))rug( jitter(x))

두개 이상의 변수의 분포를 비교하는데

유용

y<-rnorm(100,5,1)par(mfrow=c(1,2)) #graphic 화면을 row 1, col 2로 분할hist(x)hist(y)

par(mfrow=c(1,1))boxplot(x,y)z<-rchisq(100,15)boxplot(x,y,z)

1 R Grahpics

Scatter plot3

y<-3+5*x+rnorm(100,0,5)plot(x,y)plot(x,y,main="main is here", xlab="x label here", ylab="y label here")p ( ,y, , , y y )

x<-runif(10,1,10)x<-sort(x)y<--5+4*x+rnorm(10,0,10) plot(x,y)plot(x,y,type="l")plot(x,y,type="b")

1 1z<--3+3*x+rnorm(10,0,1) lines(x,z,type="b",col=2,pch=2,lty=2)legend(8,10,c("2011","2012"),lty=1:2,col=1:2)

plot(x,y,type="b",cex=2) #cex는 symbol 크기 등을 조절

Page 18: 1부 R프로그램 Tutorial

16

Scatter plot3

1 R Grahpics

1 R Graphics

Conditional plot4

lattice package가 필요함.library(lattice)library(lattice)Depth <- equal.count(quakes$depth, number=8, overlap=.1)xyplot(lat ~ long | Depth, data = quakes)

histogram(~height | voice.part, data = singer,main="Distribution of Heights by Voice Pitch",xlab="Height (inches)")xlab= Height (inches) )

• R Graph에 대해 좋은 책• Visualizing Data (William S. Cleveland)• Lattice: Multivariate Data Visualization with R (Deepayan Sarkar)

Page 19: 1부 R프로그램 Tutorial

17

2 Linear Model

이 장에서는 linear model에 대해서 알아본다. 기본적으로 반응변수(Y)와 설명변수(X)가 pair로 관측되며 반응변수가 설명변수들의 선형식으로 표현될 수 있다고 가정한다. 회귀계수 추정은 기본적으로least-squares 방법론을 사용한다. (회귀분석 전 과정에서 Graph를 적극적으로 활용하자.)

A. Basic model fittinglm1<-lm(y~ x1+x2+x3, data=mydata)summary(lm1)

우리가 사용할 data는 mtcars. 반응변수는 mpg, 나머지는 모두 설명변수.head(mtcars)summary(mtcars)plot(mtcars)

lm1<-lm(mpg~., data=mtcars)summary(lm1) #coef, std.err, t-value, p-value, R-sq’d, F-stat, etc.

predict(lm1,mtcars) #예측치

2 Linear Model

B. Model Performance

좋은 모델이란 무엇인가?• Goodness of fit : 관측치(observed) 와 예측치(fitted)가 비슷해야 한다 RSS (또는• Goodness of fit : 관측치(observed) 와 예측치(fitted)가 비슷해야 한다. RSS (또는MSE)가 작아야 한다. • Model simplicity : 간단한 모형이 좋은 모형이다. 선형모형에서는 설명변수의 수가 적어야 한다.

위의 두 조건은 서로 다른 방향으로 작용하기 때문에 동시에 개선하는 것은 어려운일이다. 위의 두 조건을 동시에 고려하는 measure를 만들자. • AIC(Akaike Information Criterion) • BIC(Bayesian Information Criterion)

둘다 weighted average of RSS and 설명변수의 수

Page 20: 1부 R프로그램 Tutorial

18

2 Linear Model

C. Variable Selection

이제 주어진 data에서 변수선택을 해보자. 우리의 목표는 AIC 값이 최소가 되는 모형을 선택하는

것이다 설명변수의 수가 너무 많지 않으면 all possible regression을 통해서 min AIC model을 찾것이다. 설명변수의 수가 너무 많지 않으면 all-possible regression을 통해서 min AIC model을 찾

을 수 있다. 하지만 설명변수의 수가 많으면, 2^p개의 모형을 적합한 후에 AIC 계산을 해야 하기

때문에 계산량이 너무 많아질 수 있다. Local search를 해보자.

• Backward Elimination : full model에서 시작해서 가장 쓸모없는 설명변수부터 제거하자.

• Forward Selection : constant model에서 시작해서 가장 쓸모있는 설명변수부터 첨가하자.

• Stepwise Regression : 매 스텝마다 BE과 FS을 수행하면서 AIC 값이 가장 작은 쪽인 모형을 선택

한다. 더 이상 AIC값을 줄일 수 없으면 stop한다.

2 Linear Model

lm2<-step(lm1,direction="both")

summary(lm2)

par(mfrow=c(1,1))

plot(mtcars$mpg,predict(lm2,mtcars),

xlab="observed",ylab="fitted")

abline(0,1,col=2)

plot(lm2)

Page 21: 1부 R프로그램 Tutorial