Summary : 다음을 R을 통하여 실습합니다. (1) R 이란? (2) R 기본 문법 (3) Tips
R progamming language는 (줄여서 R) 통계 계산과 그래픽을 위한 프로그래밍 언어이자 소프트웨어 환경으로 뉴질랜드 오클랜드 대학의 로스 이하카와 로버트 젠틀맨에 의해 개발되었으며 GPL 라이센스로 배포되어 비용에 부담없이 자유롭게 사용할 수 있는 언어입니다. R은 통계 소프트웨어 개발과 자료 분석에 널리 사용되고 있으며, 패키지 개발이 용이하여 통계학자들 뿐만 아니라 각종 계량 연구를 하는 분야에서 널리 사용되고 있습니다. 특히 R은 많은 연구자들에 의해 새롭게 만들어진 최신의 알고리즘과 로직들을 Package 형태로 제공하여 다른 어떤 통계 소프트웨어들보다도 다양한 분석방법 등을 제공합니다.
R은 오픈소스 패키지의 집합체이다.
R은 데이터 분석에 특화된 프로그래밍 언어로서 자유로운 자료 분석을 가능하게 합니다. Script와 command Line 에서 입력하는 방식을 취하고 있어 초기 접근이 다른 통계 소프트웨어보다 불편하게 느껴질 수 있지만 익숙해지면 그 어떤 것보다 편하게 다룰 수 있습니다.
구글링하면 좋은 자료가 진짜 많이 나옵니다!!!!!! 구글링을 생활화합시다!
R 을 잘 소개해둔 블로그
R은 공식 홈페이지에서 다운받을 수 있습니다. 자신이 사용하는 컴퓨터의 운영체제(OS)를 확인해주세요. 여기서는 Windows인 경우에 대하여 소개하겠습니다. 비트 수 확인 방법: 시작>컴퓨터>마우스 우클릭>시스템 정보>시스템 종류.
동영상 튜토리얼: How to install R for Windows
다운 받는 곳(윈도우): 영어
위에서 소개한 R-Gui만으로도 좋지만 R에는 사용자 친화적인 R 통합 개발환경 (R Integrated Development Environment)인 RStudio가 있습니다. Rstudio에서는 R에서 할 수 있는 것은 모두 할 수 있으며, R의 결과물과 문서작업을 같이하게 해주는 R markdown, c++와 함께 구현할 수 있는 Rcpp, interactive document를 구현할 수 있는 shiny 등 멋진 기능들이 많습니다.
(소개) R markdown은 R code와 문서(설명)를 pdf나 html 파일과 같이 통합된 문서로 만들어줍니다.(그것도 아주 쉽게!!) 기존의 R-Gui 환경에서 문서 작성은 거의 불가능한 수준입니다만, RStudio에서는 knitr라는 Package를 이용하여 손쉽게 만들 수 있습니다. 자세한 설명은 아래의 홈페이지로 대신하도록 하겠습니다. 본 문서도 RStudio의 여러 기능 중 하나인 R markdown으로 작성되었습니다.
R Programming에 관한 자료들이 상당히(!!!) 많습니다. R Cookbook, The Art of R Programming과 같은 세련된 유료 컨텐츠들이 있습니다만, 그에 상응하는 수준의 무료 컨텐츠가 많습니다. 여기서는 아래 2가지 정도만 소개하겠습니다. 절대 아래의 참고자료가 최고인 것은 아니며, 구글링 하면 더 좋은 자료들도 많이 보실 수 있습니다.
R 기초입문 (저자 미상, 한국어) -> R 입문에 좋은 재료입니다. (이 lecture note는 여기서 많이 참고 했습니다.)
R reference card (Tom Short 저술, 영어) -> 아주 유용한 함수들과 간략한 설명이 있습니다. (추천), R 기본 함수도 많으니 참고해주세요~
R을 이용한 데이터 처리 및 분석 실무 -> 인터넷에 공개된 무료자료 입니다! 간단하지만 처음 시작엔 좋은 것 같습니다~
R-Gui 실행
R-Gui에서 console 와 script window 개념 알기.
text_to_say <- 'Hello world!' #under score case vs camel case
print(text_to_say)
## [1] "Hello world!"
R에서는 계산기로서의 기본 산술연산을 할 수 있습니다.
3 + 2 #더하기
3 - 2 #빼기
3 * 2 #곱하기
3 / 2 #나누기
3 ^ 2 #제곱
9 %% 2 #나머지
exp(1) #지수함수
log10(1000) #로그함수
결과가 TRUE or FALSE인 논리연산을 할 수 있습니다. 논리를 작성할 때 유용합니다.
5 < 5 #크기비교 1
5 <= 5 #크기비교 2
5 > 5 #크기비교 3
5 >= 5 #크기비교 4
5 == 5 #동등비교 1
5 != 5 #동등비교 2
x <- TRUE; y = FALSE #T/F 할당
x | y #OR 함수
x & y #AND 함수
isTRUE(x) #TRUE 확인 함
정의와 계산을 해봅시다. vector는 c(), :, seq, rep 이라는 함수를 사용해서 정의할 수 있습니다. 각 명령어 마다 정의하는 방법이 다르니 알아둡시다. matrix의 정의는 matrix()라는 함수를 이용합니다. R의 계산 원칙은 element-wise입니다. 따라서 matrix multiplication을 할 때는 %*%을 사용해야합니다.
my.vector.1 <- c(1,2,3,4,5,6)
my.vector.2 <- 1:6
my.vector.3 <- seq(1,6)
my.vector.4 <- rep(1,6)
my.vector.1;my.vector.2;my.vector.3;my.vector.4
length(my.vector.1) #vector 길이
my.vector.1[3] #vector index 이용하기1 !!!! C나 python과 달리 R의 index는 1부터 시작합니다!!!!
my.vector.1[c(2,4,6)] #vector index 이용하기2
my.vector.1[-c(2,4,6)] #vector index 이용하기3
my.matrix.1 <- matrix(my.vector.1, nrow=2) #Matrix 만들기1
my.matrix.2 <- matrix(my.vector.1, nrow=3) #Matrix 만들기2
my.matrix.1;my.matrix.2;t(my.matrix.1)
dim(my.matrix.1) #Matrix 크기 확인1
nrow(my.matrix.1) #Matrix 크기 확인2
ncol(my.matrix.1) #Matrix 크기 확인3
my.matrix.2[1,2] #Matrix index 접근1
my.matrix.2[2,1] #Matrix index 접근2
my.matrix.1 * 2 #Matrix 연산1
my.matrix.1 * my.matrix.1 #Matrix 연산2
my.matrix.1 %*% my.matrix.2 #Matrix 연산3
List는 각 원소에 어떠한 object도 입력할 수 있는 변수입니다. R package의 결과물은 List형태의 결과가 많으니 알아둡시다.
name <- c("철수", "영희", "길동")
age <- c(21, 20, 31)
gender <- factor(c("M", "F", "M"))
my.list <- list(name, age, gender, 1:7)
my.list[[1]];my.list[[2]];my.list[[3]];my.list[[4]]
my.list[[1]][2]
List형 변수와 비슷하지만 벡터의 길이가 같아야 한다는 제한이 있습니다.
character <- data.frame(name, age, gender)
character;character$name;character$age;character$gender;
character[character$gender == "F", ];
character[character$age < 30 & character$gender=="M", ];
Question, 남자 데이터는 어떻게 가져올 수 있을까요?
option이 매우 많습니다. 자주사용하는 option 중에는 pch(포인터 모양), cex(포인터 크기), col(색깔)등 이 있습니다. 자세한 내용은 reference card에서 확인해보길!
str(Puromycin)
PuroTrt <- subset(Puromycin, state=="treated")
PuroUnTrt <- subset(Puromycin, state=="untreated")
plot(rate ~ conc, data=PuroTrt);
plot(rate ~ conc, data=PuroTrt, xlim=c(0, 1.2), ylim=c(40, 210), xlab="concentration(ppm)", ylab="rates(counts/min/min)", cex.lab=1.2)
plot(rate ~ conc, data=PuroTrt, pch=16, col=3, cex=1.5)
legend("bottomright", col=3, pch=16, "green point") ;
par(mfrow=c(1, 3))
plot(rate ~ conc, data=PuroTrt, type="p");
plot(rate ~ conc, data=PuroTrt, type="l");
plot(rate ~ conc, data=PuroTrt, type="b");
조건에 따라서 서로다른 프로그램을 실행하고 싶을 때, if-else if-else statement를 이용할 수 있습니다.
case <- 2
if( case == 1){
data <- 1
}else if(case == 2){
data <- 3
}else{
data <- 8
}
print(data)
반복 작업을 하는 경우 for와 while을 사용해서 반복작업을 실행할 수 있습니다. 두 함수의 사용 방법이 다르니 때에 맞춰서 잘 사용합시다.
sum <- 0 # 초기값 설정
for(x in 1:6){
sum <- sum + x
}
print(sum)
sum <- 0 # 초기값 설정
count <- 0
while( count <= 6 ){
sum <- sum + x
count <- count + 1
}
print(sum)
R 에는 계산에 편리한 여러 기본 함수가 있습니다. 아래 함수들은 많이 알 수록 좋습니다! 참고
dim(), head(), tail(), str(), rbind(), cbind(), sort(), order(), cat()
mean(), sd(), sum(), colMeans(), colSums(), log(), cos(), sin(), tan(), abs(), sqrt(), eigen()
rnorm(), qnorm(), pnorm(), dnorm()
runif(), qunif(), punif(), dunif()
rt(), qt(), pt(), dt()
function() 이라는 함수를 통해서 나만의 함수를 만들 수 있습니다. 아래에는 normal 분포에서 10개를 sample하여, sample mean을 계산하는 함수를 만드는 예제입니다.
X <- rnorm(10)
# Define a function calculating average of given data.
calculate_mean <- function(data=1:10){
mean_X <- sum(data)/length(data)
return(mean_X)
}
print(c(mean(X), calculate_mean()))
print(c(mean(X), calculate_mean(X)))
실제 자료를 잘 분석하기 위해서 data engineering (data preprocessing) 과정은 필수적입니다. 여기서는 아주 짧게 자료를 다루기에 유용한 package인 dplyr와 ggplot2을 소개하겠습니다. package를 설치하는 명령어는 install.packages(‘package_name’) 입니다.
install.packages('dplyr')
dplyr package는 자료를 받아서 처음 가공하는 과정에 매우 유용하게 사용할 수 있는 package 입니다. 주요 함수로는 glimpse(), tbl_df(), 그리고 chain operator ‘%>%’가 있습니다.’%>%’ 연산자는 x %>% f(y)를 f(x,y) 로 계산해주는 연산자 입니다. 여기서는 iris data를 사용해보겠습니다! (Dataset iris는 현대 통계학의 아버지 Fisher가 수집한 자료로서 붓꽃의 종류(setosa, versicolor, virginica) 에 따라 꽃받침길이, 꽃받침폭, 꽃잎길이 등을 기록한 자료입니다.)
library(dplyr)
## Warning: package 'dplyr' was built under R version 3.3.2
##
## Attaching package: 'dplyr'
## The following objects are masked from 'package:stats':
##
## filter, lag
## The following objects are masked from 'package:base':
##
## intersect, setdiff, setequal, union
data(iris)
glimpse(iris) # 데이터 살짝보기, str()과 head() 함수의 역할
head(iris)
tail(iris)
tbl_df(iris)
iris$Petal.Width # 변수에 접근하기
iris[, c("Petal.Length", "Petal.Width")] # 여러변수에 접근하기
iris %>% head
iris %>% select(Petal.Length, Petal.Width) #Chain operator
summary(iris$Petal.Width) # basic statistics
hist(iris$Petal.Width)
자료의 행을 필터링하여 조건에 만족하는 행만 뽑도록 도와주는 함수 filter(), 순서대로 정렬하도록 해주는 arrange() 함수를 이용해봅시다.
filter(iris, Petal.Length>3 & Petal.Length<4)
iris %>% filter(Petal.Length>3 & Petal.Length<4) #같은 결과 출력
iris %>% arrange(Petal.Length) %>% head(10) # %>% 중복 사용가능 !
이외에도 select(), mutate(), group_by(), slice(), summaraize() 등 유용한 함수가 많습니다. 참고하기 좋은 웹사이트
ggplot2
ggplot2는 R에서 제공하는 기본 plot을 ’효과적’으로 그려주는 package 입니다. 여기서 ’효과적’이라고한 이유는 단순히 예쁘게 그려주는 것 이상의 기능을 가지고 있기 때문입니다!
ggplot()의 형태는 일반적으로, ggplot(data=‘data_name’) +
처음에는 함수의 형태가 생소하게 느껴질 수도 있지만 powerful visualization을 위해서 매우 추천드립니다~
library(ggplot2)
## Warning: package 'ggplot2' was built under R version 3.3.2
ggplot(data=iris) + geom_point(mapping=aes(x=Petal.Length, y=Petal.Width))
ggplot(data=iris) + geom_point(mapping=aes(x=Petal.Length, y=Petal.Width, color=Species))
ggplot(data=iris) + geom_point(mapping=aes(x=Petal.Length, y=Petal.Width, color=Species, shape=Species))
ggplot(data=iris) + geom_point(mapping=aes(x=Petal.Length, y=Petal.Width, color=Species, shape=Species, size=Sepal.Length))
ggplot(data=iris) + geom_smooth(mapping=aes(x=Petal.Length, y=Petal.Width))
## `geom_smooth()` using method = 'loess'
ggplot(data=iris) + geom_point(mapping=aes(x=Petal.Length, y=Petal.Width)) + geom_smooth(mapping=aes(x=Petal.Length, y=Petal.Width))
## `geom_smooth()` using method = 'loess'
앞서 배운 dplyr은 ggplot2를 만날 때 최고의 시너지효과를 냅니다! 아래는 간단한 예시입니다.
iris %>% ggplot(aes(x=Petal.Length)) + geom_histogram() #히스토그램
## `stat_bin()` using `bins = 30`. Pick better value with `binwidth`.
iris %>% ggplot(aes(Petal.Length)) + geom_bar(binwidth = 0.1)
## Warning: `geom_bar()` no longer has a `binwidth` parameter. Please use
## `geom_histogram()` instead.
iris %>% ggplot(aes(Petal.Length)) + geom_bar(binwidth = 0.4) #bandwidth 변화
## Warning: `geom_bar()` no longer has a `binwidth` parameter. Please use
## `geom_histogram()` instead.
iris %>% ggplot(aes(Petal.Length, ..density..)) + geom_bar(binwidth = 0.4) + geom_density(aes(Petal.Length, ..density.. )) # density line
## Warning: `geom_bar()` no longer has a `binwidth` parameter. Please use
## `geom_histogram()` instead.
iris %>% ggplot(aes(Petal.Length)) + geom_bar(binwidth = 0.4) + coord_flip() # x,y축 변환
## Warning: `geom_bar()` no longer has a `binwidth` parameter. Please use
## `geom_histogram()` instead.
아래와 같이 연속형 변수가 2개 이상일 때 scatter plot을 그려볼 수 있습니다. facet_grid() 함수를 사용해서 visualization을 확장해보세요~
iris %>% ggplot(aes(x=Petal.Length, y=Petal.Width)) + geom_point() # scatter plot
iris %>% ggplot(aes(x=Petal.Length, y=Petal.Width)) + geom_point() + geom_smooth() # scatter plot + smooth curve
## `geom_smooth()` using method = 'loess'
iris %>% ggplot(aes(x=Petal.Length, y=Petal.Width)) + geom_point(colour='red', size=3) + geom_smooth() # scatter plot + smooth curve
## `geom_smooth()` using method = 'loess'
iris %>% ggplot(aes(x=Petal.Length, y=Petal.Width)) + geom_point(colour='red', size=3) + geom_smooth() + facet_grid(Species ~. ) # scatter plot + smooth curve + by Species.
## `geom_smooth()` using method = 'loess'
ggplot2는 매우 시각화에 있어 ’효과적’인 package 입니다. 구글링을 하면 수 없이 많은 자료를 확인할 수 있으니 앞으로 분석할 때 큰 도움이 되리라 생각합니다!
Disclaimer : 이 자료는 최영근 조교님의 2013년 가을 Survival anlysis 실습 수업자료와 권재명 선생님(서울대 계산통계학과 선배님)의 데이터 과학(가제) 책을 바탕으로 만들어졌습니다.