Applied/Statistical Learning

1. Data Exploration

TaeTrix 2023. 5. 5. 12:14
# 0. Install "ISLR2" package
install.packages("ISLR2")
library(ISLR2)

# 1. Preparation of "Auto" Dataset

#dimension 392 * 9
dim(Auto)
View(Auto)
head(Auto)

#mission value 확인
sum(is.na(Auto))

#na.omit로 missing value 제거하면 dimension 392 * 9
Auto <- na.omit(Auto)
dim(Auto)
names(Auto)

 

# 2. Exploration of "Auto" Dataset

plot(Auto$cylinders, Auto$mpg)

attach(Auto)
plot(cylinders, mpg)

# 변수 structure반환
str(Auto$cylinders)
cylinders <- as.factor(cylinders)

plot(cylinders, mpg)
plot(cylinders, mpg, col = "red", varwidth = T)
plot(cylinders, mpg, col = "red", varwidth = T, horizontal = T)

hist(mpg)
hist(mpg, col = 2, breaks = 15)


#전체 변수에 대한 correlation
pairs(Auto)
#전체 변수 중 correlation이 있는 변수만 가져와서 보겠다
pairs(~ mpg + displacement + horsepower + weight, data = Auto)

# 3. Let's prepare & explore "Boston housing" data

#(1) Read & integrate "housing1.csv" & "housing2.csv" with the same format.

setwd("/Users/kimtaestu/Downloads")
housing1 <- read.csv("housing1.csv")
dim(housing1)
head(housing1)

#header = T 불러온 data 첫줄을 변수이름으로 할 것이다.
#불러온 data에 변수 이름이 없으면 첫 줄데이터를 변수이름으로 하게 되는데 
#만약 변수 이름이 없다면 첫줄 data자체가 변수이름으로 설정이 됨으로써 행이 하나빠짐
#header = F 불러온 data 첫줄을 변수이름으로 하지 않을 것이다.

housing2 <- read.csv("housing2.csv", header = F)
dim(housing2)
head(housing2)

names(housing1)
housing1 <- housing1[,-1]
names(housing1)

#housing1에 있는 변수 이름을 housing2변수이름으로 똑같이 넣겠다
colnames(housing2) <- names(housing1)

#rbind data를 아래위로 통합
#cbind data를 양옆으로 통합
housing <- rbind(housing1,housing2)
dim(housing)
head(housing)
names(housing)
#(2) Find & delete a case whose crim value is not correct.
boxplot(housing$crim)
sum(is.na(housing$crim))
sort(housing$crim)

#outlier 확인
which(housing$crim < 0)
#outlier 제거
housing <- housing[-123,]
dim(housing)
#(3) Find a case whose medv value is missing & impute it by median.

boxplot(housing$medv)

#missing value 확인
sum(is.na(housing$medv))

#missing value가 있는 행을 반환
which(is.na(housing$medv))

#missing value를 뺀 데이터의 중앙값으로 imputation
housing$medv[45] <- median(housing$medv[-45])
sum(is.na(housing$medv))
#(4) Explore the refined housing data, and find 
#    continous variables seemed to be correlated with medv 

attach(housing)
plot(crim, medv)
plot(rm, medv)
plot(age, medv)

pairs(housing)
pairs(~ crim + rm + age + ptratio + lstat + medv, data = housing)

#(5) Transform medv into a binary response
# (new.medv = 1 if medv >= Q3, new.medv = 0 otherwise)
q <- summary(medv)
a[5]

sum(is.na(medv))
medv <- na.omit(medv)
q3 <- quantile(medv, probs=0.75)

new.medv <- rep(0,length(medv))

#new.medv에서 medv>=q3인 부분을 1로 
new.medv[medv >= q3] <- 1

sum(new.medv)
sum(medv >= q3)