19. R EDA, ๋ฐ์ดํฐ์ ์ฒ๋ฆฌ ์ฐ์ต๋ฌธ์
01. mtcars ๋ฐ์ดํฐ์ ์ qsec(1/4๋ง์ผ ์์์๊ฐ) ๋ณ์๋ฅผ ๋์์ผ๋ก ๊ทน๋จ์น(์์ 0.3%)๋ฅผ ๋ฐ๊ฒฌํ๊ณ , ์ ์ ํ์ฌ mtcars_df ์ด๋ฆ์ผ๋ก ์๋ธ์ ์ ์์ฑํ์์ค.
library(ggplot2)
str(mtcars) # 'data.frame': 32 obs. of 11 variables:
(1) ์ด์์น ํต๊ณ ํ์ธ
boxplot(mtcars$qsec)$stats # 1/4๋ง์ผ ์์์๊ฐ
์ผ๋ฐ์ ์ผ๋ก ์ํ์ 0.3% ๊ทน๋จ์น๋ก ๋ณธ๋ค.
(2) ์๋ธ์
์์ฑ : subset() ์ด์ฉ
mtcars_sub = subset(mtcars, qsec >= 14.5 & qsec <= 20.22)
(3) ์ ์ ๊ฒฐ๊ณผ ํ์ธ : boxplot() ์ด์ฉ
boxplot(mtcars_sub$qsec)
02. ๋ณธ๋ฌธ์์ ์์ฑ๋ dataset2์ resident ์นผ๋ผ์ ๋์์ผ๋ก NA ๊ฐ์ ์ ๊ฑฐํ ํ dataset5 ๋ณ์์ ์ ์ฅํ์์ค.
๋ฐฉ๋ฒ1) subset ์ด์ฉ : ํน์ ์นผ๋ผ ๊ฒฐ์ธก์น๊ฐ ์๋ ๊ฒฝ์ฐ
dim(dataset2)
dataset5 = subset(dataset2, !(is.na(dataset2$resident)) )
dim(dataset5)
๋ฐฉ๋ฒ2) na.omit ์ด์ฉ
dataset5 = dataset2
resident = na.omit(dataset2$resident) # ํน์ ์นผ๋ผ๋ง ๊ฒฐ์ธก์น ์ ๊ฑฐ
dataset5$resident = resident
03. ๋ณธ๋ฌธ์์ ์์ฑ๋ dataset2์ ์ง๊ธ(position) ์นผ๋ผ์ ๋์์ผ๋ก 1๊ธ -> 5๊ธ, 5๊ธ -> 1๊ธ ํ์์ผ๋ก ์ญ์ฝ๋ฉํ์ฌ position2 ์นผ๋ผ์ ์ถ๊ฐํ์์ค.
position = dataset2$position
cprosition = 6 - position # ์ญ์ฝ๋ฉ
dataset2$position2 = cprosition # ์นผ๋ผ ์ถ๊ฐ
04. dataset2์ gender ์นผ๋ผ์ ๋์์ผ๋ก 1->"๋จ์", 2->"์ฌ์" ํํ๋ก ์ฝ๋ฉ ๋ณ๊ฒฝํ์ฌ gender2 ์นผ๋ผ์ ์ถ๊ฐํ๊ณ , ํ์ด ์ฐจํธ๋ก ๊ฒฐ๊ณผ๋ฅผ ํ์ธํ์์ค.
dataset2$gender2[dataset2$gender == 1] <- "๋จ์"
dataset2$gender2[dataset2$gender == 2] <- "์ฌ์"
table(dataset2$gender2)
๋จ์ ์ฌ์
119 87
pie(table(dataset2$gender2))
05. ๋์ด๋ฅผ 30์ธ ์ดํ -> 1, 31~55 -> 2, 56์ด์ -> 3 ์ผ๋ก ๋ฆฌ์ฝ๋ฉํ์ฌ age3 ์นผ๋ผ์ ์ถ๊ฐํ ํ age, age2, age3 ์นผ๋ผ๋ง ํ์ธํ์์ค.
dataset2$age3[dataset2$age <= 30] = 1
dataset2$age3[dataset2$age > 30 & dataset2$age <= 55] = 2
dataset2$age3[dataset2$age > 55] = 3
dataset2[c(age,age2,age3)] # ๊ฒฐ๊ณผํ์ธ
06. ์ ์ ๋ dataset2๋ฅผ ๋์์ผ๋ก ์์
๋๋ ํฐ๋ฆฌ(c:/itwill/2_Rwork/output)์ cleanData.csv ํ์ผ๋ช
์ผ๋ก ๋ฐ์ดํ์ ํ ์ด๋ฆ์ ์ ๊ฑฐํ์ฌ ์ ์ฅํ๊ณ , new_data๋ณ์๋ก ์ฝ์ด์ค์์ค.
(1) ์ ์ ๋ ๋ฐ์ดํฐ ์ ์ฅ
write.csv(dataset2, 'cleanData.csv', row.names = F, quote = F)
(2) ์ ์ฅ๋ ํ์ผ ๋ถ๋ฌ์ค๊ธฐ/ํ์ธ
new_data <- read.csv('cleanData.csv')
07. user_data.csv์ return_data.csv ํ์ผ์ ์ด์ฉํ์ฌ ๊ฐ ๊ณ ๊ฐ๋ณ ๋ฐํ์ฌ์ ์ฝ๋(return_code)๋ฅผ ๋์์ผ๋ก ๋ค์๊ณผ ๊ฐ์ด ํ์๋ณ์๋ฅผ ์ถ๊ฐํ์์ค.
<์กฐ๊ฑด1> ๋ฐํ์ฌ์ ์ฝ๋์ ๋ํ ํ์๋ณ์ ์นผ๋ผ๋ช
์ค๋ช
์ ํ์ด์(1) : return_code1, ๋ณ์ฌ
(2) : return_code2,
์์ธ๋ถ๋ช
(3) :> return_code3, ๊ธฐํ
(4) : return_code4
return_data = read.csv('return_data.csv')
head(return_data)
user_id return_code
1 1008 1
2 1009 2
library(reshape2)
return_df = dcast(return_data, user_id ~ return_code, length)
head(return_df)
user_id 1 2 3 4
1 1008 1 0 0 0
2 1009 0 1 0 0
table(return_data$return_code)
names(return_df) <- c('user_id','return_code1','return_code2','return_code3','return_code4')
head(return_df)
<์กฐ๊ฑด2> ๊ณ ๊ฐ๋ณ ๋ฐํ์ฌ์ ์ฝ๋๋ฅผ ๊ณ ๊ฐ์ ๋ณด(user_data) ํ
์ด๋ธ์ ์ถ๊ฐ(join)
user_return_data = join(user_data, return_df, by='user_id')
head(user_return_data, 10)