R - 데이터 결측치

2020. 9. 18. 22:31R

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
# test3.R
# 데이터 정제(빠진 데이터, 이상한 데이터 제거)
# 결측치, 이상치 제거 정제
 
df <- data.frame(sex = c("M""F""NA""M""F"),
                 score = c(5534, NA))
df
 
# 결측치 확인
is.na(df)
table(is.na(df))
table(is.na(df$sex))
table(is.na(df$score))
# 결측치 포함 score 평균
mean(df$score)# NA
sum(df$score)# NA
 
# 결측치 제거
library(dplyr)
# score에서 NA 출력
df %>% filter(is.na(score))
# score 에서 NA제외 출력
df %>% filter(!is.na(score))
 
df_nona <- df %>% filter(!is.na(score))
mean(df_nona$score)
sum(df_nona$score)
 
df_nona2 <- df %>% filter(!is.na(score) & !is.na(sex))
df_nona2
# NA 모두 제거
df_nona3 <- na.omit(df)
df_nona3
 
#NA 제외 평균,합
mean(df$score, na.rm = T)
sum(df$score, na.rm = T)
 
df %>% summarise(mean_score = mean(score)) # NA
df %>% summarise(mean_score = mean(score, na.rm = T))
 
df %>% summarise(mean_score = mean(score, na.rm = T),
                 cnt = n())
# 결측치 대체하기 (평균 대체)
mean(df$score, na.rm = T)
# 평균-> NA 대체
df_test <- df
df_test
df_test$score <- ifelse(is.na(df_test$score), 4, df_test$score)
df_test
table(is.na(df_test$score))
 
# P171 이상치 정제
# 존재 할수 없는 값
out <- data.frame(sex = c(121321),
                  score = c(543426))
out
table(out$sex)
table(out$score)
 
#sex = 3이면 NA로 변경
out$sex <- ifelse(out$sex == 3, NA, out$sex)
out$sex
# score 5보다 크면 NA
out$score <- ifelse(out$score > 5, NA, out$score)
out$score
 
# out %>% filter na제외 %>% sex 그룹 %>% 요약
# score 평균
 
out %>% filter(!is.na(sex) &
                 !is.na(score)) %>% group_by(sex) %>% summarise(mean_score = mean(score))
 
# P181
# 산점도 , 막대그래프, 빈도 그래프
# 선그래프 - 시간에 따라 달라지는 데이터 표현
# 환율, 주가지수 시간에 따라 변하는지를 선 그래프 표현
 
line <- data.frame(day = c(123456),
                   score = c(543426))
library(ggplot2)
ggplot(data = line, aes(x = day, y = score)) + geom_line()
 
# 산점도 - 변수간 관계 표현
# 나이 소득 관계    키 몸무게 관계
point <- data.frame(age = c(102030405060),
                    sal = c(10100200300350100))
ggplot(data = point, aes(x = age, y = sal)) + geom_point() + xlim(2050+
  ylim(100300)
 
# 막대그래프 - 집단 간 차이 표현
# 데이터의 크기를 막대의 길이로 표현
# 성별로 소득차이 그래프
col <- data.frame(gender = c(12),
                  sal = c(300200))
ggplot(data = col, aes(x = gender, y = sal)) + geom_col()
 
# 빈도막대그래프  데이터 개수를 그래프
bar <- data.frame(score = c(543426))
ggplot(data = bar, aes(x = score)) + geom_bar()
 
cs

 

데이터 결측치란 데이터 값이 비어있는지 확인하는 것인데 비어 있는지 확인하려면 is.na(?)로? 에 

확인할 DataFrame이나 컬럼을 넣어주면 확인이 가능하다.  

데이터들을 주고 그래프로 표현해보았다. 

library(ggplot2)로 그래프를 표현하기 위해 라이브러리를 받아와서 사용하는데

aes(x=?, y=?) 이것으로 x값과 y값을 정해준다. 선 그래프라면  geom_line()이고

선점도 그래프는 geom_point(), 막대그래프는 geom_col(), 빈도 그래프는 geom_bar()를 선언해서 사용하면 된다.

'R' 카테고리의 다른 글

R - 외부데이터받아오기  (0) 2020.09.18
R - data.frame  (0) 2020.09.18
R - 변수선언  (0) 2020.09.18