3과목 · 데이터 분석·17장
R 언어
R의 기본 문법, 자료형과 자료구조, 함수·제어문, 패키지 생태계(tidyverse·ggplot2), 데이터 분석 실무 흐름을 정리합니다.
1. R이란
R 은 통계 계산·그래픽·데이터 분석을 위한 오픈소스 언어.
- 통계학자들이 만들고 유지
- 패키지 생태계가 강력
- ADsP 3과목 실기 문제의 기준 언어
2. 기본 문법
2-1. 할당
x <- 5 # 권장
y = 10 # 가능 (함수 인자에선 이것)
assign("z", 3)
2-2. 산술·비교·논리 연산자
- 산술:
+, -, *, /, ^, %% (나머지), %/% (몫) - 비교:
==, !=, >, <, >=, <= - 논리:
&, |, !(벡터) /&&, ||(스칼라)
3. 자료형
| 자료형 | 예 | 확인 |
|---|---|---|
| numeric | 3.14 | is.numeric() |
| integer | 5L | is.integer() |
| character | "abc" | is.character() |
| logical | TRUE | is.logical() |
| factor | 범주 | is.factor() |
4. 자료구조
4-1. 벡터
v <- c(1, 2, 3)
v[2] # 2
v[v > 1] # 인덱싱
length(v)
4-2. 행렬
m <- matrix(1:12, nrow = 3, ncol = 4)
m[1,] # 1행
m[,2] # 2열
4-3. 리스트
lst <- list(name = "kim", age = 30, hobbies = c("coding", "reading"))
lst$name
lst[["age"]]
4-4. 데이터프레임
df <- data.frame(
id = 1:3,
name = c("a","b","c"),
score = c(90, 85, 88)
)
df$name
df[df$score > 85, ]
4-5. 팩터
- 범주형. 레벨 순서 지정 가능.
grade <- factor(c("A","B","C","A"), levels = c("C","B","A"), ordered = TRUE)
5. 제어문
# if
if (x > 0) {
print("positive")
} else {
print("not positive")
}
# for
for (i in 1:5) print(i)
# while
i <- 1
while (i <= 3) {
print(i); i <- i + 1
}
# apply 계열 (반복문 대체)
apply(m, 1, sum) # 행 합
sapply(v, function(x) x^2)
6. 함수 정의
mean2 <- function(x, trim = 0) {
x <- sort(x)
n <- length(x)
k <- floor(n * trim)
mean(x[(k+1):(n-k)])
}
mean2(1:10, trim = 0.1)
7. 패키지 생태계
7-1. base R
- 기본 내장
7-2. tidyverse (dplyr, tidyr, ggplot2, readr, purrr)
library(dplyr)
df |>
filter(score > 80) |>
group_by(grade) |>
summarise(avg = mean(score))
7-3. 시각화 — ggplot2
library(ggplot2)
ggplot(mtcars, aes(mpg, hp, color = as.factor(cyl))) +
geom_point() +
geom_smooth(method = "lm") +
theme_minimal()
7-4. 모델링
- stats: lm, glm, aov
- randomForest
- caret (표준 인터페이스)
- xgboost
8. 데이터 입출력
# CSV
df <- read.csv("data.csv")
write.csv(df, "out.csv", row.names = FALSE)
# Excel
library(readxl); read_excel("data.xlsx")
# DB
library(DBI); dbConnect(RSQLite::SQLite(), ":memory:")
9. 대표 분석 예
9-1. 단순 회귀
model <- lm(mpg ~ hp + wt, data = mtcars)
summary(model)
predict(model, newdata = data.frame(hp = 120, wt = 3))
9-2. 분류
library(randomForest)
rf <- randomForest(Species ~ ., data = iris, ntree = 300)
importance(rf)
9-3. 군집
km <- kmeans(iris[,1:4], centers = 3)
table(km$cluster, iris$Species)
9-4. 시계열
library(forecast)
fit <- auto.arima(AirPassengers)
plot(forecast(fit, h = 12))
10. R 함수 외우기 빈출
| 함수 | 역할 |
|---|---|
str() |
구조 확인 |
summary() |
요약 통계 |
head(), tail() |
앞/뒤 |
table() |
빈도표 |
cor() |
상관 |
cbind(), rbind() |
결합 |
merge() |
조인 |
NA, is.na(), na.omit() |
결측 |
11. R vs Python
| 축 | R | Python |
|---|---|---|
| 강점 | 통계·시각화·논문 | 범용·ML·딥러닝·서비스 |
| 커뮤니티 | 학계·통계 | 산업·AI |
| 문법 | 벡터 중심 | 객체 지향 |
| ADsP | 기본 언어 | 출제 낮음 |
12. 출제 포인트
- 대표 자료구조(벡터·리스트·데이터프레임)
- 팩터의 의미
- apply 계열 함수
- tidyverse 파이프 문법
- 기초 모델링 함수(
lm,glm,kmeans,randomForest)
요약 체크리스트
- R에서 할당 연산자 형태
- 벡터·리스트·데이터프레임 차이
- apply/sapply/lapply 구분
- lm/glm의 용도
- ggplot2의 기본 구조(ggplot + geom + aes)