목차
R 설치
R의 사용자 인터페이스
데이터 입력
데이터 관리
그래프 기본
통계 기본
맺음말
R의 설치
R 사이트에 접속 후 모듈 다운로드 CRAN (Comprehensive R Archive Network)
http://www.cran.r-project.org/index.html
http://www.cran.r-project.org/
더블클릭하여 설치 시작
R 실행
R의 특징 – Why R?
오픈소스 소프트웨어 – 자유 + 무료 출현 배경은 S 언어.
기본 명령(함수) + 외부 packages 설치
특징 어떤 환경에서든 사용 가능 (Windows, Unix, MacOS).
프로그래밍 가능.
그래픽 기능이 뛰어남.
인터프리터 언어(interpreted language)이며 대소문자 구별.
함수형 언어 • 대부분의 함수결과는 다른 함수에 입력되어 사용
• 모든 데이터 object는 메모리 상에서 이용됨.
R의 사용자 인터페이스
R 사용자 인터페이스 <목차>
작업공간 (Workspace)
입출력
할당 (Assignment)
Packages
작업 시작 환경의 Customizing
특수한 출력 지정
Batch 처리
결과의 재사용
작업공간 (Workspace)
사용자 인터페이스 명령어 방식
• 대화식: > 프롬프트에서 명령어 입력
• source() 명령어에 R의 스크립트 파일 지정
그래픽 환경 • 기본 설치된 R의 메뉴 이용 또는 GUI 기반의 R을 별도로 설치 사용
R의 작업공간 둘러보기
R은 기본적으로 명령어 사용 방식. (프롬프트는 >)
그래픽 환경에 대한 많은 노력 진행 RStudio
R Commander
…
기본원리 – 함수와 객체 기본 내장: vectors, matrices, data frames, lists, functions
사용자 작성: 함수 및 object를 프로그래밍하여 사용
편리한 기능 작업종료 시 작업공간의 이미지 저장 후 다음 작업 시 reload 가능.
위/아래방향의 화살표 key를 통해 명령어 history기능을 이용
통상 프로젝트 별로 물리적 폴더를 배정. • MS Windows 사용자의 경우:
• 잘못된 예 c:\mydocuments\myfile.txt • 왜냐하면 R에서 "\“는 escape character.
• 올바른 예: c:\\my documents\\myfile.txt 또는
• c:/mydocuments/myfile.txt
편리한 기능 – 계속 – 주석 (comment)
• ‘#’를 이용
도움말 기능: help.start() # general help
help(foo) # help about function foo
?foo # same thing
example(foo) # show an example of function foo
RSiteSearch("foo") # help 매뉴얼 및 mailing lists 검색
History기능 history() # 디폴트는 최근 사용된 25개 명령어 목록
savehistory(file="myfile") # 작업내역을 저장 (".Rhistory“가
디폴트)
loadhistory(file="myfile") # 앞서의 작업내역을 이용
맛보기: 계산기 기능 > 5+4
> 7^2
> log(10)
> exp(1)
R 설치하면 많은 예제 데이터가 제공됨. 사용 가능한 dataset을 보려면:
data( ) # Load된 package에 따라 결과는 다르다.
개별 dataset의 세부 내용을 보려면: help(datasetname)
Session별 환경 option help(options) # 이용 가능한 options
options() # 현재 설정된 option 상황
작업 디렉토리 getwd() # 현재 디렉토리 - cwd
ls() # 현재 workspace에 있는 object 목록
setwd(mydirectory) # mydirectory로 이동
setwd("c:/docs/mydir") # MS Windows에서도 \ 대신 /를 이용할 것
오류메시지 > sqrt(-2)
[1] NaN
경고메시지:
In sqrt(-2) : NaN이 생성되었습니다
> absolute(3)
에러: 함수 "absolute"를 찾을 수 없습니다
끝내기 > q()
입출력
입력 source( ) 함수이용
• 현행 session의 script 수행 (디폴트는 현재 디렉토리) source("myfile") # script파일의 적용
출력 sink( ) 함수 - 출력 방향을 지정.
sink("myfile", append=FALSE, split=FALSE) # 출력을 파일로 지정
sink() # 출력을 터미널 화면으로 복구
• append option - 덮어 쓸지 또는 추가할지를 지정.
• split option – 출력 파일과 함께 화면출력도 할지를 지정. # 예: 출력을 특정 파일로 지정 (해당 이름의 파일을 엎어 쓴다)
sink("c:/projects/output.txt")
# 예: 출력을 특정 파일로 지정 (기존 파일에 내용 추가, 화면에도 동시에 출력)
sink("myfile.txt", append=TRUE, split=TRUE)
그래픽 출력 • sink( )대신 다음의 함수를 이용
• dev.off( ) – 화면출력으로 복원.
jpeg("c:/mygraphs/myplot.jpg") # 다른 곳에 저장 시 full path 지정
plot(x)
dev.off()
Function Output to
pdf("mygraph.pdf") pdf 파일
win.metafile("mygraph.wmf") windows metafile
png("mygraph.png") png 파일
jpeg("mygraph.jpg") jpeg 파일
bmp("mygraph.bmp") bmp 파일
postscript("mygraph.ps") postscript 파일
할당 (Assignment)
변수에 값을 배정하는 것
R에서는 =, <-, <<- 를 사용할 수 있다. 그 밖에 =, <<- 도 사용 가능
할당된 객체는 메모리를 차지 rm() 불필요한 객체를 메모리에서 제거
> x=5; y=2
> x+3
[1] 8
> x+y
[1] 7
> print(x+y)
[1] 7
> x=pi
> x
[1] 3.141593
> rm(x)
패키지 (Package)
Package = R 함수, 데이터 및 컴파일된 코드의 모음.
R 최초 설치 시 base package 제공 기타 필요한 것은 별도 설치.
Library Package가 저장된 디렉토리로서 load 시켜야 사용이 가능
.libPaths() # library 위치 확인
library() # library 내에 존재하는 packages 목록
search() # 현재 load되어 있는 packages 목록
Packages 추가 ① 다운로드 설치 (한번만 하면 됨). install.packages(package명)
② CRAN Mirror사이트 선택. (e.g. Korea)
③ 현재의 session에 load (session당 한번만 실시) library(package명)
작업 시작환경의 Customization
R은 항상 Rprofile.site 파일을 먼저 수행. MS Windows: C:\Program Files\R\R-n.n.n\etc directory.
Rprofile 파일은 홈 디렉토리 또는 별도 디렉토리에 저장 가능.
Rprofile.site 파일 찾는 순서 • 현행 디렉토리 > 사용자의 홈 디렉토리
Rprofile.site 파일에는 2개의 함수를 지정 가능 .First( ) – R session 시작될 때 수행
.Last( ) – R session이 종료할 때 수행
Batch 처리
일괄처리 방식 (non-interactively) 처리 MS Windows의 경우 (경로명은 조절)
"C:\Program Files\R\R-2.13.1\bin\R.exe" CMD BATCH
--vanilla --slave "c:\my projects\my_script.R"
Linux의 경우 R CMD BATCH [options] my_script.R [outfile]
처리결과의 재 사용
출력결과를 화면에 출력 lm(mpg~wt, data=mtcars)
결과는 화면 출력되지만 저장되지 앟는다.
출력결과를 별도의 object에 저장 fit <- lm(mpg~wt, data=mtcars)
결과는 fit이라는 이름으로 저장되며 화면에는 출력되지 않음
출력결과의 내역정보 str(fit) # view the contents/structure of "fit"
"fit"라는 이름의 list에 대한 관련 정보를 수록.
데이터 입력
데이터 입력 <목차>
데이터 기초
데이터 타입
데이터 끌어오기 (Importing)
키보드 입력
DBMS의 액세스
데이터 보내기 (exporting)
Dataset에 대한 정보 획득
변수의 Labels
결측치 (Missing Data)
날짜/시간 데이터
데이터 기초
데이터와 데이터셋 (dataset) 데이터
데이터셋 • 여러 관측값을 가지는 것
• 위 데이터를 data vector로 저장할 때 c()를 이용 > Rev_2012 = c(110,105,120,140) # 예: 분기별 매출
> Rev_2013 = c(105,115,140,135)
> Revenue = cbind(Rev_2012, Rev_2013) # column별로 결합
> Revenue
Rev_2012 Rev_2013
[1,] 110 105
[2,] 105 115
[3,] 120 140
[4,] 140 135
>
R의 데이터 형태 (mode) 숫자형 (numeric)
• 숫자로만 이루이진 것 (문자가 들어있으면 전체가 문자형으로 바뀜)
문자형 (character) • “ “ 또는 ‘ ‘로 표시
논리값 (logical value: TRUE, FALSE) • 내부적으로 TRUE는 1, FALSE는 0
• 0이외의 숫자는 TRUE로 여겨짐
데이터 형태의 변환 데이터 형태 확인
is.numeric() is.character()
is.vector() is.matrix()
is.data.frame()
데이터 변환 함수 (뒷면)
~ 로 변환 변환함수 규칙
숫자형 (numeric) 데이터
as.numeric FALSE 0 “1”,”2” 1,2
논리형 (logical) 데이터 as.logical 0 FALSE
문자형 데이터 as.character 1,2 - “1”,”2” FALSE “FALSE”
Factor as.factor 범주형 (factor) 형태로 변경
Vector as.vector 벡터 형태로 변화
Matrix as.matrix Matrix 형태로 변환
데이터프레임 as.dataframe 데이터프레임 형태로 변환
데이터 벡터 > x = c(1,3,5,7)
> x
[1] 1 3 5 7
문자 벡터 > family = c("아버지", "어머니","딸","아들")
> family
[1] "아버지" "어머니" "딸" "아들"
논리벡터 > c(T,T,F,T)
[1] TRUE TRUE FALSE TRUE
> x = -5:3
> x
[1] -5 -4 -3 -2 -1 0 1 2 3
> w = x < -2
> w
[1] TRUE TRUE TRUE FALSE FALSE FALSE FALSE FALSE FALSE>
R의 데이터 타입 vectors (numerical, character, logical)
• scalars
Matrices
Arrays
data frames
lists.
데이터 타입 – Vector
… a <- c(1,2,5.3,6,-2,4) # numeric vector
b <- c("one","two","three") # character vector
c <- c(TRUE,TRUE,TRUE,FALSE,TRUE,FALSE) #logical vector
Vector의 개별 항목 (elements)은 첨자 (subscripts)로 지정
[]로 표시 a[c(2,4)] # 2번째와 4번째 항목
> new_a <- a[-2] # 2번째 항목을 제외
> new_a
[1] 1.0 5.3 6.0 -2.0 4.0
데이터 타입 – Matrices
각 column은 같은 mode(숫자 또는 문자 등)의 데이터 column내 수록된 항목의 개수는 일정
일반형 mymatrix <- matrix(vector, nrow=r, ncol=c, byrow=FALSE,
dimnames=list(char_vector_rownames, char_vector_colnames))
byrow=TRUE
• matrix 의 내용을 row 우선으로 채운다. byrow=FALSE
• matrix 의 내용을 Column 우선으로 채운다. (디폴트). dimnames
• column 및 row에 대한 optional labels 지정 y<-matrix(1:20, nrow=5,ncol=4) # 5 x 4 numeric matrix 생성
또 다른 예 cells <- c(1,26,24,68)
rnames <- c("R1", "R2")
cnames <- c("C1", "C2")
mymatrix <- matrix(cells, nrow=2, ncol=2, byrow=TRUE,
dimnames=list(rnames, cnames))
row, column 및 항목의 식별은 첨자 (subscripts)를 이용 x[,4] # matrix의 4째 column
x[3,] # matrix의 3째 row of
x[2:4,1:3] # 2,3,4번 row의 1,2,3번 column
참조: 행렬의 계산
> x = c(1,2,3,4,5)
> y = c(-1,-2,-3,-4,-5)
> # x+ y
> x+y
[1] 0 0 0 0 0
> # x'y
> t(x) %*% y
[,1]
[1,] -55
> # xx'
> x %*% t(x)
[,1] [,2] [,3] [,4] [,5]
[1,] 1 2 3 4 5
[2,] 2 4 6 8 10
[3,] 3 6 9 12 15
[4,] 4 8 12 16 20
[5,] 5 10 15 20 25
> # 각 성분의 곱
> x * y
[1] -1 -4 -9 -16 -25
> # x, y를 합쳐 두 개의 열을 가진 행렬로 만들기
> new_matrix = cbind(x,y)
> new_matrix
x y
[1,] 1 -1
[2,] 2 -2
[3,] 3 -3
[4,] 4 -4
[5,] 5 -5
> # 행렬의 차원
> dim(new_matrix)
[1] 5 2
>
데이터 타입 – Array
Matrices와 동일하나 2차원 이상의 항목을 가진다. 예: 4 x 3 x 2의 3차원 배열에 1~24의 값을 입력 > x <- array(1:36, c(4,3,3))
> x[1,,]
[,1] [,2] [,3]
[1,] 1 13 25
[2,] 5 17 29
[3,] 9 21 33
> x[,,1]
[,1] [,2] [,3]
[1,] 1 5 9
[2,] 2 6 10
[3,] 3 7 11
[4,] 4 8 12
데이터 타입 – Data Frame
Column마다 다른 모드(숫자, 문자, factor 등)의 항목을 가질 수 있다.
d <- c(1,2,3,4)
e <- c("red", "white", "red", NA)
f <- c(TRUE,TRUE,TRUE,FALSE)
mydata <- data.frame(d,e,f)
names(mydata) <- c("ID","Color","Passed") # 변수 명
data frame의 항목 식별: myframe[3:5] # 3,4,5번 column
myframe[c("ID","Age")] # ID 및 Age columns
myframe$X1 # x1 변수
데이터 타입 – List
객체목록으로서 항목의 순서가 의미를 가지는 것 (An ordered collection of objects). 하나의 이름으로 다양한 (possibly unrelated) 객체를 저장 가능.
# example of a list with 4 components -
# a string, a numeric vector, a matrix, and a scaler
w <- list(name="Fred", mynumbers=a, mymatrix=y, age=5.3)
# example of a list containing two lists
v <- c(list1,list2)
항목의 식별은 [[]] 를 이용. mylist[[2]] # 2nd component of the list
mylist[["mynumbers"]] # component named mynumbers in list
데이터 타입 – Factor
변수가 명목변수일 때 사용 각 항목은 [ 1... k ] 범위의 숫자 vector로 인식
factor() 및 ordered() 함수의 option을 통해 문자와 순서 사이의 대응관계를 조절할 수 있다.
factor를 이용해서 value label을 만들 수도 있다. # 예: 20명의 "male(남성)"과 30명 "female(여성)"을 가지는 gender라는 변수
gender <- c(rep("male",20), rep("female", 30))
gender <- factor(gender)
# R은 gender를 nominal 변수로 처리. (내부적으로 1=female, 2=male)
summary(gender)
순서변수는 ordered factor를 이용 # 예: "large", "medium", "small'로 지정된 rating이라는 변수
rating <- ordered(rating)
# 이 경우 rating변수를 ordinal로 처리 (1=large, 2=medium, 3=small)
몇 가지 유용한 함수들
length(object) # object가 가진 항목의 개수
str(object) # object의 구조
class(object) # object의 class 또는 type
names(object) # names
c(object,object,...) # 객체를 결합(combine) vector를 만듬.
cbind(object, object, ...) # combine objects as columns
rbind(object, object, ...) # combine objects as rows
object # object를 출력
ls() # 현재의 object 목록을 출력
rm(object) # object 삭제
newobject <- edit(object) # 복사하여 새로 생성
fix(object) # 곧바로 수정, 변경
데이터 끌어오기 (Importing)
Import from: csv 텍스트 파일 첫 줄은 변수의 이름, 항목 구분자(separator)는 comma
각 줄(row)에는 변수 번호 (id) 적용
MS Windows의 경우 \ 대신 / 를 사용
mydata <- read.table("c:/mydata.csv", header=TRUE,
sep=",", row.names="id")
Import from: Excel CSV 파일로 저장한 후 앞서의 방법을 이용할 수 있다.
MS Windows – RODBC package 이용. 첫째 row는 column 명.
library(RODBC)
channel <- odbcConnectExcel("c:/myexel.xls")
mydata <- sqlFetch(channel, "mysheet")
odbcClose(channel)
키보드 입력 SAS, SPSS, Excel, Stata, DB, ASCII 파일에서 import할 때:
# create a data frame from scratch
age <- c(25, 30, 56)
gender <- c("male", "female", "male")
weight <- c(160, 110, 220)
mydata <- data.frame(age,gender,weight)
R의 자체 편집기를 이용할 수 있다. # enter data using editor
mydata <- data.frame(age=numeric(0), gender=character(0),
weight=numeric(0))
mydata <- edit(mydata)
DBMS의 액세스
RODBC package ODBC interface.
주요 함수:
Function Description
odbcConnect(dsn, uid="", pwd="") ODBC 데이터베이스에 connection open
sqlFetch(channel, sqtable) ODBC DB 테이블을 읽어서 data frame에 가져옴
sqlQuery(channel, query) Submit a query to an ODBC database and return the results
sqlSave(channel, mydf, tablename
= sqtable, append = FALSE)
Write or update (append=True) a data frame to a table in the ODBC database
sqlDrop(channel, sqtable) ODBC 데이터베이스에서 table 제거
close(channel) Close the connection
# 예:DBMS의 2개 테이블(Crime & Punishment)을
# 2개의 R 데이터프레임 (crimedat & pundat)으로 import
library(RODBC)
myconn <-odbcConnect("mydsn", uid="Rob", pwd="aardvark")
crimedat <- sqlFetch(myconn, Crime)
pundat <- sqlQuery(myconn, "select * from Punishment")
close(myconn)
기타의 Interfaces RMySQL package –interface to MySQL.
ROracle package – interface for Oracle.
RJDBC package – JDBC interface.
데이터 보내기 (exporting)
Tab Delimited Text File write.table(mydata, "c:/mydata.txt", sep="\t")
Excel Spreadsheet library(xlsReadWrite)
write.xls(mydata, "c:/mydata.xls")
Dataset에 대한 정보 획득
ls() # objects 목록 출력
names(mydata) # mydata에 있는 변수 목록
str(mydata) # mydata의 구조 출력
levels(mydata$v1) # mydata의 v1 factor의 level
dim(object) # object의 차원 (dimensions)
class(object) # object (numeric, matrix, data frame, etc)의 class
mydata # mydata 출력
head(mydata, n=10) # mydata의 맨 앞 10개 row 출력
tail(mydata, n=5) # mydata의 맨 뒤 5개 row 출력
Value Labels
factor 함수를 통해 자체의 value label을 만들 수 있다. # 작업목표: 변수 v1이 1=red, 2=blue, 3=green의 값을 가지도록 함
mydata$v1 <- factor(mydata$v1,
levels = c(1,2,3),
labels = c("red", "blue", "green"))
# variable y is coded 1, 3 or 5
# we want to attach value labels 1=Low, 3=Medium, 5=High
mydata$v1 <- ordered(mydata$y,
levels = c(1,3, 5),
labels = c("Low", "Medium", "High"))
nominal 데이터는 factor(), ordinal 데이터는 ordered() 이용.
결측치 (Missing Data)
결측치는 NA (not available)로 표시된다.
불능값 (예: dividing by zero)는 NaN (not a number)로 표시. 문자, 숫자에 상관없이 같은 symbol 사용
결측치 여부 검사 is.na(x) # TRUE of x가 결측치면 TRUE를 반환
y <- c(1,2,3,NA)
is.na(y) # vector (F F F T) 변환
결측치에 대한 대처 mydata$v1[mydata$v1==99] <- NA # v1 변수에서 99값은 결측치로 해석
분석 시 결측치를 배제하지 않으면 결과 자체가 결측치가 된다. x <- c(1,2,NA,3)
mean(x) # returns NA
mean(x, na.rm=TRUE) # returns 2
complete.cases() – complete 여부에 따라 논리값 출력. # list rows of data that have missing values
mydata[!complete.cases(mydata),]
na.omit() – 결측값 제거 # 결측치는 생략한 채 처리하여 결과를 newdata에 저장
newdata <- na.omit(mydata)
기타의 결측치 처리 R 함수 별 옵션 이용.
날짜/시간 (Date) 데이터
1970-01-01 이후의 날자 수로 표현 (음수는 이전 시점 표시).
# as.Date( ) – string을 date로 변환
mydates <- as.Date(c("2007-06-22", "2004-02-13"))
# number of days between 6/22/07 and 2/13/04
days <- mydates[1] - mydates[2]
Sys.Date( ) – 오늘
date() – 현재 날짜 및 시간
다음은 format( ) 함수에서 이용 가능한 symbol.
예: 오늘 날짜 출력 today <- Sys.Date()
format(today, format="%B %d %Y")
"June 20 2007"
Symbol 의미 예
%d day as a number (0-31) 01-31
%a
%A 단축 형 요일 표시 비 단축 형 요일 표시
Mon Monday
%m month (00-12) 00-12
%b
%B 단축 형 월 표시 비 단축 형 월 표시
Jan January
%y
%Y 2-digit year 4-digit year
07 2007
날짜 변환 문자 날짜
• as.Date(x, "format") 함수 이용.
• x는 문자데이터, format은 필요한 포맷 지정. # date 정보를 'mm/dd/yyyy'포맷으로 변환
strDates <- c("01/05/1965", "08/16/1975")
dates <- as.Date(strDates, "%m/%d/%Y")
• 디폴트 포맷: yyyy-mm-dd mydates <- as.Date(c("2007-06-22", "2004-02-13"))
날짜 문자
• as.Character( ) 함수 이용. strDates <- as.character(dates)
데이터 관리
데이터 관리 <목차>
새로운 변수의 생성
연산자 (Operators)
내장 함수
제어문
사용자 작성 함수
데이터의 정렬
데이터 병합 (Merge)
Aggregating Data
Reshaping Data
Subsetting Data
apply() 함수
새로운 변수의 생성
치환 연산자 <- 를 이용 다음 3가지 중 하나 선택 가능
mydata$sum <- mydata$x1 + mydata$x2
mydata$mean <- (mydata$x1 + mydata$x2)/2
attach(mydata)
mydata$sum <- x1 + x2
mydata$mean <- (x1 + x2)/2
detach(mydata)
mydata <- transform( mydata,
sum = x1 + x2,
mean = (x1 + x2)/2
)
변수를 Recoding하기
# 예1: 2개의 나이별(age) 범주 그룹(categories)를 생성
mydata$agecat <- ifelse(mydata$age > 70,
c("older"), c("younger"))
# 예2: 3개의 age categories를 생성
attach(mydata)
mydata$agecat[age > 75] <- "Elder"
mydata$agecat[age > 45 & age <= 75] <- "Middle Aged"
mydata$agecat[age <= 45] <- "Young"
detach(mydata)
연산자 (Operators)
Binary 연산자는 vector, matrix 및 scalar 모두에 적용됨.
Arithmetic Operators
Operator Description
+ 더하기
- 빼기
* 곱하기
/ 나누기
^ or **
지수 (제곱)
x %% y 나머지 (x mod y) 5%%2 is 1
x %/% y
integer division 5%/%2 is 2
Logical Operators
Operator Description
< less than
<= less than or equal to
> greater than
>= greater than or equal to
== exactly equal to
!= not equal to
!x Not x
x | y x OR y
x & y x AND y
isTRUE(x) test if X is TRUE
# 예:
x <- c(1:10)
x
1 2 3 4 5 6 7 8 9 10
x > 8
F F F F F F F F T T
x < 5
T T T T F F F F F F
x > 8 | x < 5
T T T T F F F F T T
x[c(T,T,T,T,F,F,F,F,T,T)]
1 2 3 4 9 10
x[(x>8) | (x<5)] # 결과: 1 2 3 4 9 10
수학함수
수학 함수
Function Description
abs(x) 절대값
sqrt(x) 제급근
ceiling(x) ceiling(3.475) 는 4
floor(x) floor(3.475) 는 3
trunc(x) trunc(5.99) 는 5
round(x, digits=n) round(3.475, digits=2) 는 3.48
cos(x), sin(x), tan(x) 이 밖에도 acos(x), cosh(x), acosh(x)등
log(x)
log10(x)
exp(x) e^x
문자함수
문자 함수
Function Description
substr(x, start=n1,
stop=n2)
문자vector에서 substring을 추출 또는 변경
grep(pattern, x ,
ignore.case=FALSE,
fixed=FALSE)
Search for pattern in x. fixed =FALSE pattern은 정규표현 식. fixed=TRUE pattern 은 텍스트 문자열이며 해당 index를 산출 grep("A", c("b","A","c"), fixed=TRUE) 2
sub(pattern,
replacement, x,
ignore.case =FALSE,
fixed=FALSE)
x에서 pattern을 찾아서 변경시킴. fixed=FALSE pattern 은 정규표현 식. fixed = T pattern은 텍스트 문자열. sub("\\s",".","Hello There") "Hello.There"
strsplit(x, split) 문자열의 지정 element를 분리 (Split).
strsplit("abc", "") 3 개의 vector로 분리. 즉, "a","b","c"
paste(..., sep="") sep으로 구분시키면서 문자열 연결 (Concatenate)
toupper(x)
tolower(x)
대문자로 변환 소문자로 변환
예 x <- "abcdef"
substr(x, 2, 4) # "bcd"
substr(x, 2, 4) <- "22222" # "a222ef"
paste("x",1:3,sep="") # c("x1","x2" "x3")
paste("x",1:3,sep="M") # c("xM1","xM2" "xM3")
paste("Today is", date())
확률 x <- pretty(c(-3,3), 30) # 표준정규곡선
y <- dnorm(x)
plot(x, y, type='l', xlab="Normal Deviate", ylab="Density",
yaxs="i")
pnorm(1.96) is 0.975
#50 random normal variates with mean=50, sd=10
x <- rnorm(50, m=50, sd=10)
# 10회 실시에서 head가 0~5 나올 확률
dbinom(0:5, 10, .5)
# 10회 실시에서 head가 5번 이하 나올 확률
pbinom(5, 10, .5)
확률 함수
확률 함수
Function Description
dnorm(x) 정규밀도함수 (default m=0 sd=1)
pnorm(q) 누적 정규 확률 (area under the normal curve to the right of q)
qnorm(p) normal quantile 즉, 정규분포 상의 p percentile의 값
rnorm(n, m=0,sd=1) n 개의 정규편차 (random normal deviates) (평균: m, 표준편차: sd).
dbinom(x, size, prob)
pbinom(q, size, prob)
qbinom(p, size, prob)
rbinom(n, size, prob)
이항분포 (size = 표본 수, prob = 확률)
dpois(x, lamda)
ppois(q, lamda)
qpois(p, lamda)
rpois(n, lamda)
poisson 분포 (m=std=lamda) # lamda=4일 때의 0,1, or 2 event가 발생할
확률
dpois(0:2, 4)
dunif(x, min=0, max=1)
punif(q, min=0, max=1)
qunif(p, min=0, max=1)
runif(n, min=0, max=1)
일양분포 (uniform distribution) #10 uniform random variates
x <- runif(10)
통계 함수
다음 통계함수에서 na.rm option을 통해 결측치 제거 후 작업. Object는 numeric vector 또는 데이터프레임.
통계함수
Function Description
mean(x, trim=0,
na.rm=FALSE)
object x의 평균 # trimmed mean, 결측치 제거 및 상하위 점수 5% mx <- mean(x,trim=.05,na.rm=TRUE)
sd(x) object(x)의 표준편차. var(x)= 분산. mad(x) = median absolute deviation.
median(x) Median
quantile(x, probs) x = 원하는 quantile의 숫자 vector probs = 숫자 vector (확률: [0,1] ) # x의 30번째와 84번째의 percentiles
y <- quantile(x, c(.3,.84))
range(x) 범위
sum(x) 합계
diff(x, lag=1) lagged differences (lag는 lag 방식 지정)
min(x) 최소값
max(x) 최대값
scale(x, center=TRUE,
scale=TRUE)
column center or standardize a matrix.
기타의 유용한 함수
기타 함수
Function Description
seq(from , to, by) 수열 (sequence) 생성 indices <- seq(1,10,2)
#indices is c(1, 3, 5, 7, 9)
rep(x, ntimes) n 회 반복 y <- rep(1:3, 2)
# y is c(1, 2, 3, 1, 2, 3)
cut(x, n) divide continuous variable in factor with n levels y <- cut(x, 5)
제어문
다음 표시 중 expr에 { }를 이용하여 복합문을 이용할 수 있다.
if-else if (cond) expr
if (cond) expr1 else expr2
for for (var in seq) expr
while while (cond) expr
switch switch(expr, ...)
ifelse ifelse(test,yes,no)
예제 - matrix의 전치(轉置) (단, 내장함수 t() 참조) # matrix의 전치(轉置) – 가급적 내장함수 t() 를 이용할 것
mytrans <- function(x) {
if (!is.matrix(x)) {
warning("argument is not a matrix: returning NA")
return(NA_real_)
}
y <- matrix(1, nrow=ncol(x), ncol=nrow(x))
for (i in 1:nrow(x)) {
for (j in 1:ncol(x)) {
y[j,i] <- x[i,j]
}
}
return(y)
}
# try it
z <- matrix(1:10, nrow=5, ncol=2)
tz <- mytrans(z)
사용자 작성 함수
사용자 함수의 표준형
myfunction <- function(arg1, arg2, ... ){
statements
return(object)
}
함수 내의 Object는 지역(local) 변수. # 예: central tendency와 분산도(spread) 계산.
mysummary <- function(x,npar=TRUE,print=TRUE) {
if (!npar) {
center <- mean(x); spread <- sd(x)
} else {
center <- median(x); spread <- mad(x)
}
if (print & !npar) {
cat("Mean=", center, "\n", "SD=", spread, "\n")
} else if (print & npar) {
cat("Median=", center, "\n", "MAD=", spread, "\n")
}
result <- list(center=center,spread=spread)
return(result)
}
# 함수 호출
set.seed(1234)
x <- rpois(500, 4)
y <- mysummary(x)
Median= 4
MAD= 1.4826
# y$center는 median (4) ,
# y$spread는 median absolute deviation (1.4826)
y <- mysummary(x, npar=FALSE, print=FALSE)
# no output
# y$center is the mean (4.052)
# y$spread is the standard deviation (2.01927)
함수명을 ( ) 없이 지정하면 소스코드를 볼 수 있다.
데이터의 정렬
order( )
디폴트는 ASCENDING.
sorting 변수 앞에 – (minus) 표시를 하면 DESCENDING order. # 예: mtcars 데이터 셋을 정렬
attach(mtcars)
# sort by mpg
newdata <- mtcars[order(mpg),]
# sort by mpg and cyl
newdata <- mtcars[order(mpg, cyl),]
#sort by mpg (ascending) and cyl (descending)
newdata <- mtcars[order(mpg, -cyl),]
detach(mtcars)
데이터 병합 (merge)
Column 추가 merge 함수 – 2개 데이터 프레임(datasets)을 수평적으로 merge
대개, 공통의 key변수에 의해 join (i.e., an inner join). # merge two data frames by ID
total <- merge(data frameA,data frameB,by="ID")
# merge two data frames by ID and Country
total <- merge(data frameA,data frameB,by=c("ID","Country"))
Rows 추가 rbind 함수 - 2개 데이터 프레임(datasets)을 수직적으로 merge.
양 데이터 프레임는 같은 변수를 가질 것. (순서는 달라도 무방). total <- rbind(data frameA, data frameB)
특정 변수가 데이터프레임 A 에는 있지만 B에는 없는 경우: • 1. Delete the extra variables in data frameA or
• 2. Create the additional variables in data frameB and set them to NA (missing) before joining them with rbind( ).
데이터 총량화 (Aggregating Data)
BY 변수와 함수지정을 통해 데이터를 압축 (collapse) # mtcars를 aggregate. 숫자변수에 대해 평균계산
attach(mtcars)
aggdata <-aggregate(mtcars, by=list(cyl,vs), FUN=mean, na.rm=TRUE)
print(aggdata)
detach(mtcars)
단, by 변수는 항상 list에 있을 것
함수는 내장, 사용자 작성 모두 가능.
참조: summarize() in the Hmisc package
summaryBy() in the doBy package
데이터의 모양 변경 (Reshaping)
전치 (轉置: Transpose) t() – transpose a matrix or a data frame.
# 예:
mtcars
t(mtcars)
Reshape Package "melt" data 각 row가 고유한 id-variable 조합의 형태가 됨.
그런 후 원하는 형태로 변경 ("cast“)
mydata
Id time x1 x2
1 1 5 6
1 2 3 5
2 1 6 1
2 2 2 4
# example of melt function
library(reshape)
mdata <- melt(mydata, id=c("id","time"))
newdata
Id Time Variable Value
1 1 x1 5
1 2 x1 3
2 1 x1 6
2 2 x1 2
1 1 x2 6
1 2 x2 5
2 1 x2 1
2 2 x2 4
# cast the melted data
# cast(data, formula, function)
subjmeans <- cast(mdata, id~variable, mean)
timemeans <- cast(mdata, time~variable, mean)
subjmeans
timemeans
melt( ) and cast( ) 함수에는 그 밖의 다양한 기능이 많음.
id x1 x2
1 4 5.5
2 4 2.5
time x1 x2
1 5.5 3.5
2 2.5 4.5
Subsetting Data
R의 indexing 기능을 통해 특정 변수 등을 선택.
변수 선택 (Keeping)의 예:
# select variables v1, v2, v3
myvars <- c("v1", "v2", "v3")
newdata <- mydata[myvars]
# another method
myvars <- paste("v", 1:3, sep="")
newdata <- mydata[myvars]
# select 1st and 5th thru 10th variables
newdata <- mydata[c(1,5:10)]
특정 변수 배제 (DROPPING) 의 예: # v1, v2, v3 변수를 배제
myvars <- names(mydata) %in% c("v1", "v2", "v3")
newdata <- mydata[!myvars]
# 3째 및 5째 변수를 배제
newdata <- mydata[c(-3,-5)]
# v3 및 v5를 삭제
mydata$v3 <- mydata$v5 <- NULL
특정 row (Observations) 선택 # 맨 앞의 5개 observerations
newdata <- mydata[1:5,]
# 변수 값에 의거하는 경우
newdata <- mydata[ which(mydata$gender=='F'
& mydata$age > 65), ]
# 또는
attach(newdata)
newdata <- mydata[ which(gender=='F' & age > 65),]
detach(newdata)
Subset 함수를 통한 선택 # 예(1): 나이가 20 이상 또는 10 미만인 사람의 ID와 Weight.
newdata <- subset(mydata,age>= 20|age < 10,select=c(ID, Weight))
# 예(2): 나이가 25 이상인 남자의 weight부터 income까지 모든 column.
newdata <- subset(mydata, sex=="m" & age > 25,
select=weight:income)
무작위 (Random) 표본 sample( ) 함수 –random sample of size n from a dataset.
# take a random sample of size 50 from a dataset mydata
# sample without replacement
mysample <- mydata[sample(1:nrow(mydata), 50, replace=FALSE),]
정리
Dates dates 는 문자 또는 숫자로 변환이 가능.
예제
to one long vector
to matrix
to data frame
from Vector
c(x,y) cbind(x,y)
rbind(x,y)
data.frame(x,y)
from Matrix
as.vector(my
matrix)
as.data.frame(
mymatrix)
from data frame
as.matrix(my
frame)
apply() 함수
행렬의 행과 열에 대해 원하는 함수를 적용 형태: apply(data, dim, function)
• dim=1 이면 각 행(row)에 function을 적용
• dim=2 이면 각 열(column)에 function을 적용
## Compute row and column sums for a matrix:
x <- cbind(x1 = 3, x2 = c(4:1, 2:5))
dimnames(x)[[1]] <- letters[1:8]
apply(x, 2, mean, trim = .2)
col.sums <- apply(x, 2, sum)
row.sums <- apply(x, 1, sum)
rbind(cbind(x, Rtot = row.sums), Ctot = c(col.sums,
sum(col.sums)))
stopifnot( apply(x,2, is.vector)) # not ok in R <= 0.63.2
apply(x, 2, sort) # column을 정렬
##- function with extra args:
cave <- function(x, c1,c2) c(mean(x[c1]),mean(x[c2]))
apply(x,1, cave, c1="x1", c2=c("x1","x2"))
ma <- matrix(c(1:4, 1, 6:8), nr = 2)
apply(ma, 1, table) #--> a list of length 2
apply(ma, 1, quantile)# 5 x n matrix with rownames
stopifnot(dim(ma) == dim(apply(ma, 1:2, sum)))
R의 그래프 기초
R의 그래프 기초 <목차>
R 그래프 개요
plot() 함수
그래프 생성
밀도 Plots
점 (Dot) Plots
막대 (Bar) Plots
선 도표 (Line Charts)
파이 차트 (Pie Charts)
상자 그림 (Boxplots)
Scatter Plots
R 그래프 개요
R에서의 다양한 그래프 기능의 예 demo(graphics); > demo(persp)
Sine 함수와 cosine 함수 이용 예: x = (0:20) * pi / 10; y = cos(x)
x = (0:20) * pi / 10
y = cos(x)
plot(x,y)
ysin = sin(x)
ysin2 = sin(x) ^2
plot(x,y)
lines(x,ysin2)
par(mfrow = c(2,2))
plot(x,y, type="p")
plot(x,y, type="l")
plot(x,y, type="b")
plot(x,y, type="p", pch=19, col="red")
그래프의 저장 그래픽 환경에서의 메뉴를 이용:
• File -> Save As.
다음의 함수를 이용.
Function Output to
pdf("mygraph.pdf") pdf 파일
win.metafile("mygraph.wmf") windows metafile
png("mygraph.png") png 파일
jpeg("mygraph.jpg") jpeg 파일
bmp("mygraph.bmp") bmp 파일
postscript("mygraph.ps") postscript 파일
여러 개의 그래프를 동시에 이용하기 새 그래프는 기존 그림을 덮어 쓰므로 이를 피하려면 다음 함수를 이용하여 새 그래프 생성 전에 미리 새 graph window를 열 것.
• 이를 통해 여러 개 graph windows를 한번에 열 수 있다.
• help(dev.cur)
또는 첫 graph window를 연 후, • 메뉴에서 History -> Recording 선택한 후 Previous 및 Next 를 이용
Function Platform
windows() Windows
X11() Unix
quartz() Mac
plot() 함수
plot( ) 함수 graph widow를 열고 plotting
대화식으로 그래프 생성 # Creating a Graph
attach(mtcars)
plot(wt, mpg)
abline(lm(mpg~wt))
title("Regression of MPG on Weight")
plot()함수의 옵션: 뒷면
파라미터 Option 및 설명
type = 그래프의 형태를 지정 type=“p” 점(point) 그래프 type=“l” 선(line) 그래프 type=“b” 점과 선으로 이어서 그림 type=“o” 선이 점 위에 겹쳐진 형태 type=“h” 수직선으로 그림 type=“s” 계단(step)형 그래프
xlim =
ylim = x축과 y축의 상한과 하한. xlim = c(1,10) 또는 xlim = range(x)
xlab =
ylba = x축과 y축의 이름(label) 부여
main = 그래프의 위쪽에 놓이는 주 제목(main title).
sub = 그래프의 아래쪽에 놓이는 소 제목(subtitle).
bg= 그래프의 배경화면 색깔
bty= 그래프를 그리는 상자의 모양
pch
lty
파라미터 Option 및 설명
pch = 표시되는 점의 모양
lty = 선의 종류 1: 실선(solid line) 2: 파선 (dashed) 3: 점선: 점선(dotted) 4: dot-dash
col= 색깔 지정 “red”,”green”,”blue” 및 색상을 나타내는 숫자
mar = c(bottom, left, top, right) 의 순서로 가장자리 여분 값을 지정. 디폴트는 c(5,4,4,2) + 0.1
예: par(mfrow = c(2,2))
plot(x,y, type="b", main = "cosie 그래프", sub = "type = b")
plot(x,y, type="o", las = 1, bty = "u", sub = "type = o")
plot(x,y, type="h", bty = "7", sub = "type = h")
plot(x,y, type="s", bty = "n", sub = "type = s")
abline() 직선
abline(a,b) # 절편=a, 기울기=b인 직선
abline(h=y) # 수평선
abline(v=x) # 수직선
abline(lm.obj) # lm.obj에 지정된 직선
예: data(cars)
attach(cars)
par(mfrow=c(2,2))
plot(speed, dist, pch=1); abline(v=15.4)
plot(speed, dist, pch=2); abline(h=43)
plot(speed, dist, pch=3); abline(-14,3)
plot(speed, dist, pch=8); abline(v=15.4); abline(h=43)
히스토그램
Histograms hist(x) 함수
• x 는 plotting하려는 값의 숫자 vector
• freq=FALSE option 빈도 대신 확률밀도
• breaks= option bin의 개수 지정
Histogram의 단점 • 구간의 개수에 크게 영향을 받는다.
# 가장 단순한 히스토그램
hist(mtcars$mpg)
# 구간의 개수를 지정. 색상 지정
hist(mtcars$mpg, breaks=12, col="red")
밀도 Plot
핵 밀도(Kernel Density) Plots plot(density(x)) 단, x는 수치 vector.
# Kernel Density Plot
d <- density(mtcars$mpg)
plot(d) # plots the results
# Filled Density Plot
d <- density(mtcars$mpg)
plot(d, main="Kernel Density of Miles Per Gallon")
polygon(d, col="red", border="blue")
Kernel Density를 이용한 Group 비교 sm package의 sm.density.compare(x, factor)
• x는 숫자 vector, factor는 grouping 변수.
• superimpose the kernal density plots of two or more groups. # Compare MPG distributions for cars with 4,6, or 8 cylinders
library(sm)
attach(mtcars)
# create value labels
cyl.f <- factor(cyl, levels= c(4,6,8),
labels = c("4 cylinder", "6 cylinder", "8 cylinder"))
# 밀도곡선의 plotting
sm.density.compare(mpg, cyl, xlab="Miles Per Gallon")
title(main="MPG Distribution by Car Cylinders")
# add legend via mouse click
colfill<-c(2:(2+length(levels(cyl.f))))
legend(locator(1), levels(cyl.f), fill=colfill)
점 plotting
점 Plotting (Dot Plot) dotchart(x, labels=)
x는 숫자 vector, labels은 각 점의 레이블.
groups= option x를 그룹화할 factor 지정.
dotchart(mtcars$mpg,labels=row.names(mtcars),
cex=.7,main="Gas Milage for Car Models",
xlab="Miles Per Gallon")
# Dotplot: 그룹별, 정렬 (기준: mpg, group), 색깔 (by cylinder)
x <- mtcars[order(mtcars$mpg),] # sort by mpg
x$cyl <- factor(x$cyl)
x$color[x$cyl==4] <- "red"
x$color[x$cyl==6] <- "blue"
x$color[x$cyl==8] <- "darkgreen"
dotchart(x$mpg,labels=row.names(x),cex=.7,groups= x$cyl,
main="Gas Milage for Car Models\ngrouped by cylinder",
xlab="Miles Per Gallon", gcolor="black", color=x$color)
막대 (Bar) Plots
barplot(height) height는 vector 또는 matrix.
• If (height is a vector) • 값에 따라 높이가 달라짐.
• If (height is a matrix AND option beside=FALSE) • 각 bar는 height column에 대응되고 값은 stacked “sub-bars”의 높이)
• If (height is a matrix AND beside=TRUE) • the values in each column are juxtaposed rather than stacked.
• option names.arg=(character vector) 막대에 대한 label
• option horiz=TRUE 수평 barplot 생성
단, Bar plot은 빈도수 외에 여타의 통계량도 bar plotting가능. (means, medians, sd 등)
• aggregate( ) 함수의 결과를 barplot( ) 에 전달하는 방식
# Simple Bar Plot
counts <- table(mtcars$gear)
barplot(counts, main="Car Distribution", xlab="Number of Gears")
# Simple Horizontal Bar Plot with Added Labels
counts <- table(mtcars$gear)
barplot(counts, main="Car Distribution", horiz=TRUE,
names.arg=c("3 Gears", "4 Gears", "5 Gears"))
Stacked Bar Plot # Stacked Bar Plot with Colors and Legend
counts <- table(mtcars$vs, mtcars$gear)
barplot(counts, main="Car Distribution by Gears와 VS에 따른 자동차
분포“, xlab="Gear의 수", col=c("darkblue","red"),
legend = rownames(counts))
Grouped Bar Plot # Grouped Bar Plot
counts <- table(mtcars$vs, mtcars$gear)
barplot(counts, main=“Gears와 VS에 따른 자동차 분포",
xlab="Gear의 수", col=c("darkblue","red"),
legend = rownames(counts), beside=TRUE)
선 도표 (Line Charts)
선 도표 (Line Charts) lines(x, y, type=)
• x와 y는 연결하고자 하는 점좌표의 숫자 vector
• type= 다음의 값을 가짐
Type Description
p 점
l 선
o overplotted points와 lines
b, c 선으로 연결(join)된 points ("c“의 경우 비었음)
s, S stair steps
h histogram-like vertical lines
n 아무 것도 출력치 않음
lines( ) function • 자체만으로는 그래프 생성 못하고 plot(x, y) 명령 후 사용됨.
• 디폴트: plot( ) plots the (x,y) points.
• plot( ) 의 type="n" option – 그래프에 점을 plotting 하지 않으면서 axes, titles 등을 만들어냄.
• only looks different from the type="b" option if the plotting of points is suppressed in the plot( ) command.
• 예: x <- c(1:5); y <- x # create some data
par(pch=22, col="red") # plotting symbol and color
par(mfrow=c(2,4)) # all plots on one page
opts = c("p","l","o","b","c","s","S","h")
for(i in 1:length(opts)){
heading = paste("type=",opts[i])
plot(x, y, type="n", main=heading)
lines(x, y, type=opts[i])
}
plot( ) 에서의 type= options 의 예 x <- c(1:5); y <- x # create some data
par(pch=22, col="blue") # plotting symbol and color
par(mfrow=c(2,4)) # all plots on one page
opts = c("p","l","o","b","c","s","S","h")
for(i in 1:length(opts){
heading = paste("type=",opts[i])
plot(x, y, main=heading)
lines(x, y, type=opts[i])
}
# Create Line Chart
Orange$Tree <- as.numeric(Orange$Tree) # factor numeric 변환
ntrees <- max(Orange$Tree)
xrange <- range(Orange$age) # x, y축의 범위
yrange <- range(Orange$circumference)
# set up the plot
plot(xrange, yrange, type="n", xlab="Age (days)",
ylab="Circumference (mm)" )
colors <- rainbow(ntrees)
linetype <- c(1:ntrees)
plotchar <- seq(18,18+ntrees,1)
# add lines
for (i in 1:ntrees) {
tree <- subset(Orange, Tree==i)
lines(tree$age, tree$circumference, type="b", lwd=1.5,
lty=linetype[i], col=colors[i], pch=plotchar[i])
파이 차트
pie(x, labels=) x 는 non-negative numeric vector (각 slice의 면적표시)
labels= • 각 slice 이름의 문자 vector
# Simple Pie Chart
slices <- c(10, 12,4, 16, 8)
lbls <- c("US", "UK", "Australia", "Germany", "France")
pie(slices, labels = lbls, main="Pie Chart of Countries")
Pie 차트에서 백분율 표시 # Pie Chart with Percentages
slices <- c(10, 12, 4, 16, 8)
lbls <- c("US", "UK", "Australia", "Germany", "France")
pct <- round(slices/sum(slices)*100)
lbls <- paste(lbls, pct) # add percents to labels
lbls <- paste(lbls,"%",sep="") # ad % to labels
pie(slices,labels = lbls, col=rainbow(length(lbls)),
main="Pie Chart of Countries")
3D Pie Chart plotrix package의 pie3D( ) function
• 3D exploded pie chart 출력 # 3D Exploded Pie Chart
library(plotrix)
slices <- c(10, 12, 4, 16, 8)
lbls <- c("US", "UK", "Australia", "Germany", "France")
pie3D(slices,labels=lbls,explode=0.1,
main="Pie Chart of Countries ")
Box Plot
상자 plot 각 변수별 또는 그룹별로 Boxplot 가능.
boxplot(x, data=) • x 는 formula, data= 에서 데이터프레임 지정
• formula 예 : y~group
• varwidth=TRUE 를 추가하면 폭이 제곱근에 비례
• horizontal=TRUE 를 추가하면 축 방향이 반대가 됨. # Boxplot of MPG by Car Cylinders
boxplot(mpg~cyl,data=mtcars, main="Car Milage Data",
xlab="Number of Cylinders", ylab="Miles Per Gallon")
# Notched Boxplot of Tooth Growth Against 2 Crossed Factors
# boxes colored for ease of interpretation
boxplot(len~supp*dose, data=ToothGrowth, notch=TRUE,
col=(c("gold","darkgreen")),
main="Tooth Growth", xlab="Suppliment and Dose")
Violin Plots Boxplot과 kernel density plot의 혼합형태.
vioplot package의 vioplot( ) library(vioplot)
x1 <- mtcars$mpg[mtcars$cyl==4]
x2 <- mtcars$mpg[mtcars$cyl==6]
x3 <- mtcars$mpg[mtcars$cyl==8]
vioplot(x1,x2,x3,names=c("4 cyl", "6 cyl", "8 cyl"),col="gold")
title("Violin Plots of Miles Per Gallon")
Scatterplots
Scatterplot의 단순한 방식 plot(x, y)
• x, y는 numeric vector로서 plot할 점 (x,y)을 표시 attach(mtcars)
plot(wt, mpg, main="Scatterplot Example",
xlab="Car Weight ", ylab="Miles Per Gallon ", pch=19)
# Add fit lines
abline(lm(mpg~wt), col="red") # regression line (y~x)
lines(lowess(wt,mpg), col="blue") # lowess line (x,y)
car package의 scatterplot( ) 다양한 기능제공.
예: fit lines, marginal box plots, conditioning on a factor, and interactive point identification.
# Enhanced Scatterplot of MPG vs. Weight by no. of Car Cylinders
library(car)
scatterplot(mpg ~ wt | cyl, data=mtcars,
xlab="Weight of Car", ylab="Miles Per Gallon",
main="Enhanced Scatter Plot", labels=row.names(mtcars))
Scatterplot Matrices 예:
pairs(~mpg+disp+drat+wt,data=mtcars,
main="Simple Scatterplot Matrix")
lattice package options to condition the scatterplot matrix on a factor.
# Scatterplot Matrices from the lattice Package
library(lattice)
splom(mtcars[c(1,3,5,6)], groups=cyl, data=mtcars,
panel=panel.superpose,
key=list(title="Three Cylinder Options", columns=3,
points=list(pch=super.sym$pch[1:3], col=super.sym$col[1:3]),
text=list(c("4 Cylinder","6 Cylinder","8 Cylinder"))))
car package factor에 따라 scatterplot matrix 조절
선택적으로: • lowess 및 linear best fit lines, boxplot, densities, histograms in
the principal diagonal, rug plots in the margins of the cells. # car Package로 부터의 Scatterplot Matrix
library(car)
scatterplot.matrix(~mpg+disp+drat+wt|cyl,
data=mtcars,
main="Three Cylinder Options")
gclus package options to rearrange the variables so that those with higher
correlations are closer to the principal diagonal. It can also color code the cells to reflect the size of the correlations.
# Scatterplot Matrices from the glus Package
library(gclus)
dta <- mtcars[c(1,3,5,6)] # get data
dta.r <- abs(cor(dta)) # get correlations
dta.col <- dmat.color(dta.r) # get colors
# 변수를 재배열해서 상관계수가 높은 것이 대각선에 가까워짐
dta.o <- order.single(dta.r)
cpairs(dta, dta.o, panel.colors=dta.col, gap=.5,
main="Variables Ordered and Colored by Correlation" )
High Density Scatterplots The hexbin(x, y) function in the hexbin package provides
bivariate binning into hexagonal cells (it looks better than it sounds).
# High Density Scatterplot with Binning
library(hexbin)
x <- rnorm(1000)
y <- rnorm(1000)
bin<-hexbin(x, y, xbins=50)
plot(bin, main="Hexagonal Binning")
sunflowerplot. # High Density Scatterplot with Color Transparency
pdf("c:/scatterplot.pdf")
x <- rnorm(1000)
y <- rnorm(1000)
plot(x,y, main="PDF Scatterplot Example",
col=rgb(0,100,0,50,maxColorValue=255), pch=16)
dev.off()
3D Scatterplots scatterplot3d package의 scatterplot3d(x, y, z).
# 3D Scatterplot
library(scatterplot3d)
attach(mtcars)
scatterplot3d(wt,disp,mpg, main="3D Scatterplot")
library(scatterplot3d)
attach(mtcars)
s3d <-scatterplot3d(wt,disp,mpg, pch=16, highlight.3d=TRUE,
type="h", main="3D Scatterplot")
fit <- lm(mpg ~ wt+disp)
s3d$plane3d(fit)
R과 기초통계
R과 기초통계 <목차>
기술통계 (記述統計)
빈도수와 Crosstabs
상관관계
t-tests
비모수 통계 (이하 생략)
회귀 진단
ANOVA/MANOVA
(M)ANOVA Assumptions
Resampling Stats
검정력분석
With와 By
기술통계 (Descriptive Statistics)
= 요약통계 (summary statistics)
sapply( ) 함수 # mydata라는 데이터프레임에서의 변수 평균. 단, 결측치는 계산에서 제외
sapply(mydata, mean, na.rm=TRUE)
sapply 에 이용 가능한 함수: • mean, sd, var, min, max, median, range, and quantile.
기타의 함수 summary(mydata) # 평균, 중위값, 1사분위/3사분위, 최소, 최대
fivenum(x) # Tukey min,lower-hinge, median,upper-hinge,max
Hmisc package library(Hmisc)
describe(mydata)
# n, nmiss, unique, mean, 5,10,25,50,75,90,95th percentiles, …
pastecs package library(pastecs)
stat.desc(mydata) # nbr.val, nbr.null, nbr.na, min max, range,
# sum, median, mean, SE.mean, CI.mean, …
psych package library(psych)
describe(mydata) # item name ,item number, nvalid, mean, sd,
# median, mad, min, max, skew, kurtosis, se
Group별 summary 통계
psych package. library(psych)
describe.by(mydata, group,...)
doBy package model formula와 함수를 통해 원하는 테이블 지정
library(doBy)
summaryBy(mpg + wt ~ cyl + vs, data = mtcars,
FUN = function(x) { c(m = mean(x), s = sd(x)) } )
# produces mpg.m wt.m mpg.s wt.s for each
# combination of the levels of cyl and vs
빈도수와 Crosstabs
빈도표 생성 table( ) frequency tables
prop.table( ) tables of proportions
margin.table( ) marginal frequencies # 2-Way Frequency Table (단, A, B, C 는 범주형 변수)
attach(mydata)
mytable <- table(A,B) # A will be rows, B will be columns
mytable # print table
margin.table(mytable, 1) # A frequencies (summed over B)
margin.table(mytable, 2) # B frequencies (summed over A)
prop.table(mytable) # cell percentages
prop.table(mytable, 1) # row percentages
prop.table(mytable, 2) # column percentages
table( ) 을 이용해서 다차원 테이블을 생성.
ftable( ) 을 통해 출력을 고급화.
mytable <- table(A, B, C) # 3-Way Frequency Table
ftable(mytable)
Table은 결측치를 무시. NA를 category의 하나로 count에 포함하려면
• if (변수가 vector): table option으로 exclude=NULL
• if (변수=factor): newfactor <- factor(oldfactor, exclude=NULL)
(즉, 새로운 factor 생성)
xtabs
xtabs( ) formula 형 입력을 통해 crosstabulations 생성 # 3-Way Frequency Table
mytable <- xtabs(~A+B+c, data=mydata)
ftable(mytable) # print table
summary(mytable) # chi-square test of indepedence
Formula의 왼쪽에 변수가 있는 경우 빈도 vector를 가정 (이미 tabulate처리된 경우 유용).
Crosstable
로그 선형(Loglinear) 모델 MASS package의 loglm( )
예: A, B, and C.변수에 따른 3-way contingency table이 있다면: library(MASS)
mytable <- xtabs(~A+B+C, data=mydata)
다음과 같은 검정을 시행할 수 있다: • 상호적 (Mutual) 독립성: A, B, C가 pairwise independent. loglm(~A+B+C, mytable)
• Partial Independence: A is partially independent of B and C (즉, A is independent of the composite variable BC). loglin(~A+B+C+B*C, mytable)
• 조건적 (Conditional) 독립성: A is independent of B, given C. loglm(~A+B+C+A*C+B*C, mytable)
• No Three-Way Interaction loglm(~A+B+C+A*B+A*C+B*C, mytable)
연관성 측도
연관성 척도 (Measures of Association)
vcd package의 assocstats(mytable) phi 계수, contingency 계수 및 Cramer's V 계산
vcd package의 kappa(mytable) 혼동 매트릭스 (confusion matrix)에 대한 Cohen's kappa 및
weighted kappa를 계산
결과의 시각화 1차원: 빈도수 시각화를 위한 bar 차트 및 pie 차트
범주형 데이터간의 관계: vcd package 이용 • 예: mosaic 및 association plots
ca package를 이용한 correspondence 분석 • 분할표의 row와 column간 관계를 시각화하여 분석
빈도표를 "Original" Flat file로 변환 테이블을 데이터 프레임으로 되돌리는 코드 (Marc Schwartz)
상관관계
cor( )
상관관계 cov( )
공분산
단순 포맷: cor(x, use=, method= ) 다음 표를 참조
Option Description
x Matrix 또는 data frame
use 결측치 처리방법. Options: all.obs (결측치 없는 것을 전제 – 결측치는 에러 발생), complete.obs (listwise deletion), pairwise.complete.obs (pairwise deletion)
method Specifies the type of correlation. Options: pearson, spearman, kendall.
# mtcars의 수치 변수간 상관관계/공분산. 결측치는 listwise deletion
cor(mtcars, use="complete.obs", method="kendall")
cov(mtcars, use="complete.obs")
cor.test( ) test a single correlation coefficient neither cor( ) or cov( ) produce tests of significance,
Hmisc package의 rcorr( ) correlations/covariances and significance levels for pearson and spearman correlations. 단, 입력항목은 matrix이고 pairwise deletion 적용.
# Correlations with significance levels
library(Hmisc)
rcorr(x, type="pearson") # pearson 또는 spearman 타입
rcorr(as.matrix(mtcars)) # mtcars는 data frame
cor(X, Y) 또는 rcorr(X, Y) column X와 column Y간의 상관관계 생상
# mtcars의 Correlation matrix
# rows: mpg, cyl, disp
# columns:hp, drat, wt
x <- mtcars[1:3]
y <- mtcars[4:6]
cor(x, y)
기타의 Correlations # polychoric 상관계수 (x = counts의 분할표)
library(polycor)
polychor(x)
# 한 matrix 내의 이형변수간 상관계수 (heterogeneous correlations)
# pearson (numeric-numeric), polyserial (numeric-ordinal),
# polychoric (ordinal-ordinal)
# x는 ordered factor와 numeric 변수를 가지는 data frame
library(polycor)
hetcor(x)
# partial correlations
library(ggm)
data(mydata)
pcor(c("a", "b", "x", "y", "z"), var(mydata))
# partial corr between a and b controlling for x, y, z
Correlation의 시각화 corrgram( )
• plot correlograms .
pairs() or splom( ) • scatterplot matrices.
t-tests
t.test( ) 기본: unequal variance를 가정하고 Welsh 자유도 modification.
t.test(y~x) # y는 numeric, x는 binary factor
# independent 2-group t-test
t.test(y1,y2) # y1와 y2는 numeric
# paired t-test
t.test(y1,y2,paired=TRUE) # y1와 y2는 numeric
# one sample t-test
t.test(y,mu=3) # Ho: mu=3
var.equal = TRUE option • equal variances와 pooled variance 추정치를 지정
• 단측검증의 경우 alternative="less" or alternative="greater"
t-test 대신 비모수 (non-parametric)및 resampling도 가능
결과의 시각화 • 집단차이를 시각화하기 위해 box plot 또는 density plot 사용.
맺음말
맺음말
수리/통계 분석도구로서의 R
프로그래밍 언어로서의 R
시각화 도구로서의 R
R의 미래
Top Related