R Preview

R의 특징

  • 통계 분석에 용이한 언어이고 무료임
  • 인터프리터 언어임 (interpreter , 해석기 ) 즉, 소스코드를 바로 실행하는 환경을 말하며, 소스 코드를 한줄 한줄 읽어들어며 실행하는 프로그램임 (ex, 자바스크립트, HTML, 액션스크립트, SQL, python, ruby)
  • S언어를 기반으로 개발한 오픈소스 프로그램임 왜 R이라 지어졌냐면, 개발한 두 사람의 이름이 R로 시작한다함 ^.^ (Robert Gentleman, Ross lhaka)
  • R은 객체지향적 설계가 가능함

R 의 장단점

장점 단점
통계분석에 활용할수 있는 패키지 많음
무료로 사용 가능
윈도우, 리눅스 , 맥 에서 동작 가능
범용 프로그래밍 언어(C, python, java)에 비해 처리속도가 느림

R 객체 지향 프로그래밍

아마 나처럼 R의 객체지향적 특징을 이용하지 않고 개발하는 사람이 많을 것이다. 긴 코드를 좀 더 엄밀함을 보이기 위한 S4 Class를 익혀보자. (S3에 비해 S4는 더 OOP에 가까우며 strict 하다.)

R의 Object - Oriented Programming (OOP)는 [[S3]], [[S4]] and [[R5]] 로 구성되어있으며 여기서는 S4를 중점으로 다룰거임.

특징 S3 S4
클래스 정의 리스트 생성후 class() setClass()
객체 생성 리스트 생성 후 속성 부여 new()
클래스 요소 접근 $ @

Classes and instances

S4는 S3와 다르게 setClasses를 사용하여 호출의 표현을 정의하며, 요소를 생성시에는 new를 사용함

setClass(name, representation, contains)

  • name : 클래스이름

  • representation : a list of slots (or attribute)

    eg. representation(name = ‘character’, age= ‘numeric’)

  • contains [optional] : 상속된 클래스의 경우, 부모클래스 명을 기재.

1
2
3
4
5
6
7
8
9
10
#-- Create Class
setClass('Person',representation(name='character',age='numeric'))
setClass('Employee',representation(boss='Person'), contains="Person")

#-- Create instance
hadley <- new('Person', name='Haldey', age=31)

#-- S3와 다르게 모든 slot의 type을 확인함.
hadley <- new("Person", name = "Hadley", age = "thirty")
#Error in validObject(.Object) : invalid class "Person" object: invalid object for slot "age" in class "Person": got class "character", should be or extend class "numeric"

객체 요소에 접근 slot()

1
2
slot(hadley, "name")
#[1] "Haldey"

S4 클래스 메소드 생성 setMethod()

setMethod(메소드이름, 클래스이름, 실행될 함수)

1
2
3
4
5
6
7
8
9
10
11
12
13
#--만약 기존에 정의된 Generic function이 없다면  생성해야함
setGeneric('Info', function(object) standardGeneric('Info'))

#--S4 클래스 메소드 생성           
setMethod('Info', 'Person', 
    function(object){
    cat(object@name, ' is ', object@age, ' years old.')
    })
Info(hadley)
# Haldey  is  31  years old.

#-- 특정 generic function에 어떤 method 가 있는가?
showMethods('Info')           

메소드를 제거하려면 removeMethod(메소드이름, 클래스이름)

참고자료 http://adv-r.had.co.nz/S4.html https://diytranscriptomics.com/Reading/files/The%20Art%20of%20R%20Programming.pdf

RData, RDS 파일 활용

RData, RDS 파일은 R 기반 데이터 파일이라 용량이 작으며 읽고 쓰는 속도가 빠르다. (RDS가 더 널리 쓰임)

  • 즉, Rdata / RDS 파일을 쓰면 데이터 저장공간을 좀 더 효율적으로 사용할 수 있음!

RData는 여러개의 object를 저장 할 수 있음

1
2
3
4
5
#-- Usage
#-- 저장
save(a, b, c, file = "test.RData")
#-- 읽기
load(file = "test.RData")

RDS 파일은 single object를 저장 할 수 있음

1
2
3
4
5
#-- Usage
#-- 저장
saveRDS(object, file = "", ascii = FALSE, version = NULL, compress = TRUE, refhook = NULL)
#-- 읽기
readRDS(file, refhook = NULL)

R studio 단축키

  • 한 줄 실행 : ctrl + enter

  • 여러줄 실행 : 블록 설정 후 ctrl + enter

  • 현재 Script 실행 : ctrl + alt + R

  • 마지막에 실행한 명령 다시 실행 : ctrl + shift + P

SPSS 파일 읽기

1
2
3
4
install.packages('foreign')
library(foreign)

dataset.raw <- read.spss('C:\Users\user\TIL\R\R_study\database\spss_eda.sav', to.data.frame=T)

KoNLP 설치

1
2
3
4
5
6
7
8
9
10
11
Sys.setenv(JAVA_HOME = 'C:\Program Files\Java\jdk1.8.0_121')
install.packages('multilinguer')
install.packages(c('stringr','hash','tau','Sejong','RSQLite','devtools'),type= 'binary')
install.packages('remotes')

remotes::install_github('haven-jeon/KoNLP', upgrade = 'never', INSTALL_opts=c('--no-multiarch'))
# install.packages('devtools')
# devtools::install_github('haven-jeon/KoNLP')

library(rJava)
library(KoNLP)

text mining

1
2
3
4
install.packages('tm')
install.packages('RColorBrewer')
library(tm)
library(KoNLP)

google API를 이용한 시각화

1
2
3
4
5
6
7
8
9
10
11
library(devtools)
library(ggmap)

googleAPIKEY ='googleAPIKEY'
register_google(googleAPIKEY)

gg_seoul <- get_googlemap('seoul', maptype = 'terrain')
ggmap(gg_seoul)

#위도 경도 추출
geo_code <- enc2utf8('대전역') %>% geocode()

Reference

R : https://www.r-project.org/

R studio: https://www.rstudio.com/