통계 이야기

[2일차] Do it! 쉽게 배우는 R 데이터 분석 / 98P~ 144P / 자유자재로 데이터 가공하기

창이 2022. 5. 5.
728x90
반응형

head() : 데이터 앞 부분 출력

tail() : 데이터 뒷 부분 출력

View() : 뷰어 창에서 데이터 확인

dim() : 데이터 차원 출력

str() : 데이터 속성 출력 

summary() : 요약 통계량 출력 

 

summary() 함수의 출력값

Min 

1st Qu

Median

Mean 

3rd Qu

Max 

 

as.data.frame 은 데이터 속성을 데이터 프레임 형태로 바꾸는 함수. 

 

어떤 데이터를 분석하든, 가장 먼저 data.frame, dim, summary 등의 함수를 활용하여

각 변수들의 전반적인 특징을 먼저 파악하는 것이 중요합니다. 

 

dplyr 패키지

filter() : 행 추출

select() : 열 추출

arrange() : 정렬

mutate() : 변수 추가

summarise() : 통계치 산출

group_by() : 집단별로 나누기

left_join() : 데이터 합치기(열) 

bind_rows() : 데이터 합치기(행)

data <- read.csv("excel_exam.csv", stringsAsFactors = F)
head(data)
head(data, 10)
View(data)
dim(data)
str(data)
summary(data)

mpg <- as.data.frame(ggplot2::mpg)
head(mpg) ; dim(mpg)
# mpg 데이터는 234개의 관측치와 11개의 변술 구성되어 있음. 
# chr은 문자, num은 소수점이 있는 실수(numeric), int는 소수점이 없는 정수(integer)

# rename 함수를 이용하기 위해 dplyr 패키지 설치
library(dplyr)
df_raw <- data.frame(var1 = c(1, 2, 1), var2 = c(2, 3, 2))
df_new <- df_raw 
df_new <- rename(df_new, v2 = var2)
df_new

# 혼자서 해보기 
mpg_new <- mpg
mpg_new <- rename(mpg_new, c(city = cty, highway = hwy))
head(mpg_new)

# 혼자서 해보기 (파생변수)
mpg$total <- (mpg$cty+mpg$hwy)/2
head(mpg)
mean(mpg$total)

hist(mpg$total)
# total 변수가 20을 넘기면 합격, 넘기지 못하면 불합격 
mpg$test <- ifelse(mpg$total >= 20, "pass", "fail")
head(mpg, 20)
library(ggplot2)
qplot(mpg$test)

mpg$grade <- ifelse(mpg$total >= 30, "A", ifelse(mpg$total >= 20, "B", "C"))
head(mpg, 20)
table(mpg$grade) ; qplot(mpg$grade)

# 분석도전
data(midwest)
head(midwest)
midwest_new <- midwest
midwest_new <- rename(midwest_new, c(total = poptotal, asian = popasian))
head(midwest_new)
midwest_new$aisanrate <- (midwest_new$asian/midwest_new$total)
mean_rate <- mean(midwest_new$aisanrate)
hist(midwest_new$aisanrate)
midwest_new$grade <- ifelse(midwest_new$aisanrate > mean_rate, "large", "small")
View(midwest_new)
table(midwest_new$grade) ; qplot(midwest_new$grade)


head(data)
data %>% filter(class == 1) # 1반 학생들만 추출 , "==" 는 같다는 의미 
data %>% filter(class == 2) # 2반 학생들만 추출
data %>% filter(class != 1) # 1반 학생들만 제외하고 추출 
data %>% filter(math > 50)
data %>% filter(english < 80)
data %>% filter(class == 1 & math >= 50)
data %>% filter(class==2 & english <= 80)
data %>% filter(math >= 90 | english <= 90)
data %>% filter(class ==1 | class == 3 | class == 5)
data %>% filter(class %in% c(1, 3, 5)) # %in%  기호는 변수의 값이 지정한 조건 목록에 해당하는지 확인하는 기능
class1 <- data%>% filter(class == 1)
mean(class1$math)

mpg_data <- mpg %>% filter(displ <= 4)
head(mpg_data)
mean(mpg_data$hwy)
mpg_data1 <- mpg%>% filter(displ >= 5)
mean(mpg_data1$hwy)

mpg_Data <- mpg%>% filter(manufacturer == "audi")
mean(mpg_Data$hwy)
mpg_Data <- mpg%>% filter(manufacturer == "toyota")
mean(mpg_Data$hwy)
mpg_Data <- mpg %>% filter(manufacturer %in% c("chevrolet", "ford", "honda"))
mean(mpg_Data$hwy)


# 필요한 변수만 추출하기
library(dplyr)
data %>% select(english)
data %>% select(class, math, english)
data %>% select(-math)
data %>% filter(class ==1) %>% select(english)
data %>%
  filter(class ==1) %>%
  select(english)
data %>%
  select(癤퓁d, math) %>%
  head(10)
mpg_var <- mpg %>% 
  select(class, cty)
head(mpg_var)
mpg_suv <- mpg_var %>%
  filter(class == "suv") 
mean(mpg_suv$cty)
mpg_compact <- mpg_var %>%
  filter(class == "compact") ; mean(mpg_compact$cty)

head(mpg_Data)
data %>% arrange(math)
data %>% arrange(desc(math))

mpg_Data <- mpg %>% 
  filter(manufacturer == "audi") %>%
  select(manufacturer, hwy) %>%
  arrange(hwy)
mpg_Data


# 파생변수 추가하기
data%>%
  mutate(total = math + english +science) %>%
  head
data %>%
  mutate(total =math + english + science, 
         mean = (math + english + science)/3) %>%
  arrange(total)%>%
  head
data %>%
  mutate(test = ifelse(science >= 60, "pass", "fail"))%>%
  head

# dplyr 패키지 함수들은 변수명 앞에 데이터 프레임 명을 반복해 입력하지 않기 때문에 코드가 간결해진다는 장점. 

# 혼자서 해보기 
library(ggplot2)
data(mpg) ; head(mpg)
mpg %>%
  mutate(hob = cty+hwy,
         m_hob = hob/2) %>%
  arrange(desc(m_hob))%>%
  head(3)

 

 

 

728x90
반응형

댓글

추천 글