-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfirst.Rmd
More file actions
374 lines (303 loc) · 8.83 KB
/
first.Rmd
File metadata and controls
374 lines (303 loc) · 8.83 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
---
title: "빅데이터 분석의 첫걸음 R코딩"
output: github_document
---
```{r setup, include = F}
knitr::opts_chunk$set(echo = T, fig.align = "center")
```
- Author: 장용식, 최진호
- Book: <https://book.naver.com/bookdb/book_detail.nhn?bid=16324211>
- coding은 example들을 제외하고는 programming으로 넘겼습니다.
---
### Big-data
_3V: volume, velocity, variety_
- 인공지능(AI) = 전문가시스템 + 퍼지시스템 + 유전알고리즘 + 기계학습
- 생성적 적대 신경망(GAN, Generative Adversarial Network): 예술 분야의 창작 활동 등에 활용할 수 있는 이미지 생성 기술
---
## 3. 데이터 구조의 이해
| 데이터 유형 | 설명 |
| ------------- | ------------------------------------------------------------------------------- |
| 벡터 | 동일한 데이터 유형(숫자 또는 문자 등)의 단일 값들이 일차원적으로 구성된 것이다. |
| 요인 | 문자 벡터에 데이터의 레벨이 추가된 데이터 구조 |
| 배열 | 동일한 데이터 유형을 갖는 1차원 이상의 데이터 구조 |
| 리스트 | 각 원소들이 이름과 서로 다른 데이터 유형을 가질 수 있다. |
| 데이터 프레임 | 2차원 테이블 형태로, 각 열의 데이터는 동일한 데이터 유형이다. |
```{r}
score <- 70
score
score <- c(70, 85, 90)
score
```
> c( ): concatenate의 약자로 벡터 생성 함수
- assign("x", c(70,80,90))보단 x <- c(70, 85, 90)을 권장한다.
```{r}
score[4] <- 100; score[3] <-95
score
name <- c("알라딘", "자스민", "지니")
name
```
### 식별자 (identifer)
- 변수 또는 함수 등을 다른 것들과 구별하기 위해 사용하는 이름들을 지칭하는 용어.
- 일련의 문자, 숫자, '.', '\_'으로 구성된다. 단, '\_'이나 숫자 + '.'으로 시작하면 안 된다.
- R에서 정의되어 있는 예약어도 사용할 수 없다.
```{r}
x <- seq(1, 10, by = 3)
x
x <- 1:10
x
x <- 10:1
x
x <- seq(1, 10, length.out = 5)
x
```
```{r}
x <- c(1,2,3)
y <- rep(x, times = 2)
y
y <- rep(x, each = 2)
y
```
### 연산자
| 산술 연산자 | 기호 | 예시 | 결과 |
| :---------: | :-------: | :------: | :------: |
| 더하기 | \+ | 2 + 3 | 5 |
| 빼기 | \- | 10 - 3 | 7 |
| 곱하기 | \* | 3\*4 | 12 |
| 나누기 | / | 4 / 3 | 1.333333 |
| 거듭제곱 | ^ or \*\* | 2^3 | 8 |
| 나머지 | %% | 10 %% 3 | 1 |
| 몫 | %/% | 10 %/% 3 | 3 |
```{r}
x <- c(10, 20, 30, 40)
y <- c(2, 4, 6, 8)
z <- c(2, 4)
x + 5
x + y
x + z
```
| 비교 연산자 | 기호 | 예 | 결과 |
| :---------: | :--: | :-----: | :---: |
| 작음 | < | 3 < 10 | TRUE |
| 이하 | <= | 3 <= 10 | TRUE |
| 큼 | > | 3 > 10 | FALSE |
| 이상 | >= | 3 >= 10 | FALSE |
| 같음 | == | 3 == 10 | FALSE |
| 같지 않음 | != | 3 != 10 | TRUE |
```{r}
3 < 10
x <- c(10, 20, 30)
x <= 10
x[x > 15]
```
```{r}
x <- c(10, 20, 30)
any(x <= 10)
all(x <= 10)
```
| 논리 연산자 | 기호 | 예 | 결과 |
| :---------: | :-------: | :-----------: | :-------------: |
| 논리합 | \| | TRUE \| FALSE | TRUE |
| 논리곱 | & | TRUE & FALSE | FALSE |
| 논리부정 | ! | !0<br />!2 | FALSE<br />TRUE |
| 진위여부 | isTRUE( ) | isTRUE(FALSE) | FALSE |
```{r}
x <- c(TRUE, TRUE, FALSE, FALSE)
y <- c(TRUE, FALSE, TRUE, FALSE)
x & y
x | y
xor(x, y)
```
> xor( ): exclusive or
| 특수값 | 기호 | |
| :----: | :--: | ----------------------------------------------------------------- |
| 결측치 | NA | 데이터 누락 |
| 널 | NULL | 변수 이름만 있는 경우 |
| (불능) | Inf | 0이 아닌 수를 0으로 나눈 경우, 수렴하지 않아 값을 특정할 수 없다. |
| (부정) | NaN | Not a number, 0을 0으로 나눈 경우와 같이 계산할 수 없는 경우 |
```{r}
x <- NULL
is.null(x)
y <- c(1, 2, 3, NA, 5)
y
z <- 10/0
z
u <- 0/0
u
```
### 요인, factor
```{r}
gender <- c('남', '여', '남')
gender
gender.factor <- factor(gender)
gender.factor
```
### 배열과 행렬
```{r}
x <- c(70, 80, 95)
arr <- array(x)
arr
z <- 1:6
arr <- array(z, dim = c(2,3))
arr
name <- list(c("국어", "음악"), c("알라딘", "자스민", "지니"))
score <- c(70, 80, 85, 90, 90, 75)
arr <- array(score, dim = c(2,3), dimnames = name)
arr
arr[1,]
arr[, 2]
```
```{r}
name <- list(c("1행", "2행"), c("1열", "2열", "3열"))
x <- 1:6
mtx <- matrix(x, nrow = 2)
mtx
mtx <- matrix(x, nrow = 2, dimnames = name, byrow = T)
mtx
y <- c(7, 8, 9)
mtx <- rbind(mtx, y)
rownames(mtx)[3] <- "3행"
mtx
z <- c(10, 11, 12)
mtx <- cbind(mtx, 2)
colnames(mtx)[4] = "4열"
mtx
```
### 리스트
```{r}
x <- list("알라딘", 20, c(70, 80))
x
x[1]
x[[1]]
x <- list(성명 = "알라딘", 나이 = 20, 성적 = c(70, 80))
x
x[1]
x[[1]]
```
### 데이터 프레임
```{r}
df <- data.frame(성명 = c("알라딘", "자스민"), 나이 = c(20, 19), 국어 = c(70, 85))
df <- cbind(df, 음악 = c(85, 90))
df
df <- rbind(df, data.frame(성명 = "지니", 나이 = 30, 국어 = 90, 음악 = 75))
df
df[3, 2]
df[3,]
df[, 2]
df[-2,]
df[, -3]
```
```{r}
df <- data.frame(성명 = c("알라딘", "자스민"), 나이 = c(20, 19), 국어 = c(70, 85))
str(df)
```
> data.frame(stringsAsFactors = T), 문자형 데이터는 다 범주화 시켜버린다.
```{r}
df[1, 2] <- 21
df
df[1, 1] <- "Aladin"
```
- 현재 성명은 범주를 알라딘, 자스민 딱 2개로 갖는 factor여서 수정 불가.
```{r}
df <- data.frame(성명 = c("알라딘", "자스민"), 나이 = c(20, 19), 국어 = c(70, 85), stringsAsFactors = F)
str(df)
df[1, 1] <- "Aladin"
df
```
### 데이터 파일 읽기
```{r}
data(package = "datasets")
```
```{r}
## quakes
head(quakes)
tail(quakes, n = 10)
names(quakes)
dim(quakes)
str(quakes)
```
```{r eval = F}
write.table(quakes, "c:/dump/quakes.csv", sep = ',')
df <- read.csv("c:/dump/quakes.csv", header = T)
head(df)
```
### 함수
_반복적인 코딩 시간의 절약, 검증된 코드 사용으로 프로그래밍 효과 up_
```{r}
getTriangleArea <- function(w, h) {
area <- w*h / 2
return(area)
}
```
```{r}
getTriangleArea(10, 5)
```
---
## 4. 무조건 해보기
```{r}
## [한국환경공단](http://www.airkorea.or.kr)
city <- c("서울", "부산", "대구", "인천", "광주", "대전", "울산")
pm25 <- c(18, 21, 21, 17, 8, 11, 25)
lat <- c(37.567933, 35.180002, 35.877052, 37.457730, 35.160331, 36.350573, 35.539865)
lon <- c(126.978054, 129.074974, 128.600680, 126.702194, 126.851433, 127.384793, 1219.311469)
```
X-Y 플로팅 차트로 보는 지역별 미세먼지 현황
```{r}
plot(lon, lat, pch = 19, cex = pm25*0.3, col = rgb(1, 0, 0, 0.3), xlim = c(126, 130), ylim = c(35, 38),
xlab = "경도", ylab = "위도")
text(lon, lat, labels = city)
```
> cex: 점의 크기를 결정하는 매개변수, 이 값이 달라서 다른 반지름을 가지게 된 것이다.
워드 클라우드로 보는 지역별 미세먼지 현황
```{r message = F}
## install.packages("wordcloud")
library(wordcloud)
```
```{r fig.width = 6, fig.height = 3}
wordcloud(city, freq = pm25, colors = rainbow(3), random.color = T)
```
애니메이션: 바람개비 돌리기
```{r eval = F}
install.packages("imager")
library(imager)
img.path <- "C://dump/pinwheel.png"
img <- load.image(img.path)
plot(img)
```
```{r eval = F}
img <- resize(img.size_z = 400L, size_y = 400L)
plot(img, xlim = c(0, 400), ylim = c(0, 400))
```
```{r eval = F}
angle <- 0
while(T) {
angle <- angle + 10
imrotate(img, angle, cx = 200, cy = 200) %>% plot(axes = F)
## pic = imrotate(img, angle, cx = 200, cy = 200); plot(pic, axes = F)
Sys.sleep(0.2)
}
```
- break 조건이 없어서 Esc를 통해 강제 종료시켜야 한다.
### 웹스크래핑: 공공데이터 포털의 API 목록 출력
```{r eval = F}
install.pakcages("rvest")
library(rvest)
```
```{r eval = F}
url <- "https://www.data.go.kr/tcs/dss/selectDataSetList.do"
html <- read.html(url)
html
```
동전 던지기 시뮬레이션
```{r}
plot(NA, xlab = "동전을 던진 횟수", ylab = "앞면이 나오는 비율", xlim = c(0, 100), ylim = c(0, 1),
main = "동전 던지는 횟수에 따른 앞면이 나올 확률 변화")
abline(h = 0.5, col = "red", lty = 2)
count <- 0
for(n in 1:100) {
coin <- sample(c("앞면", "뒷면"), 1)
if(coin == "앞면") count = count + 1
prob <- count / n
points(n, prob)
Sys.sleep(1)
}
```