1장-R의 활용(회귀분석)

Updated:

2 minute read

R의 역사

  1. 1980년대 통계 프로그램 언어로 S가 개발됨
  2. Ross Ihaka and Robert Gentleman이 교육목적으로 S의 축소버전 ‘R&R’을 만듬
  3. Martin Maechler가 Open Source Software 규약인 GPL(General Public Licence) 규약 하에 R을 공개
  4. 1997년 국제적인 R core team이 결성되고 현재 20명 2000년 2월 29일 R 1.0 발표

R의 활용

Vectorized arithmetic

> weight <- c(60, 72, 57, 90, 95, 72)
> height <- c(1.75, 1.80, 1.65, 1.90, 1.74, 1.91)
> bmi <- weight/height^2
> bmi
[1] 19.59184 22.22222 20.93664 24.93075 31.37799 19.73630

> mean(weight)
[1] 74.33333
> sd(weight)
[1] 15.42293

> # Logical Vectors
> bmi > 25
[1] FALSE FALSE FALSE FALSE  TRUE FALSE

> # Character 연결
> c("H", "D", "L")
[1] "H" "D" "L"
> cat(c("H", "D", "L"))
H D L

> # 특정 문자 기입할 때는 \를 앞에 써줄 것

> # 결측치 확인
> rowSums(is.na(wd))
> colSums(is.na(wd))
> na.omit(wd)

> # 결측치 변경
> nwd[nwd > 0.9] == 99
> nwd[nwd == 99] = NA

> # 벡터 연결
> x <- c(1,2,3)
> y <- c(10, 20)
> c(x, y, 5)
[1]  1  2  3 10 20  5

> # 벡터 생성
> seq(4,9)
[1] 4 5 6 7 8 9

> rep(oops, 3)
[1]  7  9 13  7  9 13  7  9 13
> rep(oops, 1:3)
[1]  7  9  9 13 13 13
> rep(1:2, c(10, 15))
[1] 1 1 1 1 1 1 1 1 1 1 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2

> # 행렬 만들기
> x <- 1:12
> dim(x) = c(3,4)
> x
     [,1] [,2] [,3] [,4]
[1,]    1    4    7   10
[2,]    2    5    8   11
[3,]    3    6    9   12
 
> matrix(1:12, nrow=3, byrow=T)
     [,1] [,2] [,3] [,4]
[1,]    1    2    3    4
[2,]    5    6    7    8
[3,]    9   10   11   12

> t(x) # 전치 행렬
     [,1] [,2] [,3]
[1,]    1    2    3
[2,]    4    5    6
[3,]    7    8    9
[4,]   10   11   12

> # 행렬곱 : t(A) %*% A
> # 역행렬 : solve(A)

> # 데이터 합치기
> cbind() # 열끼리 붙이기
> rbind() # 행끼리 붙이기
> cbind(A=1:4, B=5:8)
     A B
[1,] 1 5
[2,] 2 6
[3,] 3 7
[4,] 4 8

> # 인자 변수 만들기
> fpain <- factor(pain, levels = 0:3) # 명목형
> edu2 <- ordered(edu2) # 순서형
> fpain <- as.numeric(pain)

> # list는 python dict와 같고, data.frame 객체도 존재

> # indexing
> intake.pre[c(1, 5)]
> intake.pre[intake.pre > 6000] # & 도 옆에 가능

> # apply 함수
> m = matrix(rnorm(12), 4)
> apply(m, 2, min) # 1이면 행, 2면 열 기준 작업 수행

> # sorting
> order(intake$post)


> # 시각화를 할 때 plot끼리 합쳐지는 건 matplotlib과 동일 (몇 그래프는 add=T 선언 필요)

Categories:

Updated: