#install.packages("dplyr")
library(dplyr)
##
## 다음의 패키지를 부착합니다: 'dplyr'
## The following objects are masked from 'package:stats':
##
## filter, lag
## The following objects are masked from 'package:base':
##
## intersect, setdiff, setequal, union
#install.packages("hflights")
library(hflights)
#glimpse(hflights)
#colSums(is.na(hflights))
#1
hf<-hflights %>% count(Dest)
head(hf)
## Dest n
## 1 ABQ 2812
## 2 AEX 724
## 3 AGS 1
## 4 AMA 1297
## 5 ANC 125
## 6 ASE 125
hf %>% filter(n==max(n)|n==min(n))
## Dest n
## 1 AGS 1
## 2 DAL 9820
# 오답: hf %>% max(hf$n)
#2 DepTime 의 결측치 갯수
table(is.na(hflights$DepTime))
##
## FALSE TRUE
## 224591 2905
sum(is.na(hflights$DepTime))
## [1] 2905
# 오답: count(is.na(hflights$DepTime))
#3 Cancelled의 건수, 취소가 1
sum(hflights$Cancelled)
## [1] 2973
hflights %>%count(hflights$Cancelled==1)
## hflights$Cancelled == 1 n
## 1 FALSE 224523
## 2 TRUE 2973
table(hflights$Cancelled)
##
## 0 1
## 224523 2973
#4 Ozone 에서 결측치 제외한 중위수 구하고, 결측치에 중위수 입력후, 평균구하기
rm(list=ls())
data(airquality)
#glimpse(airquality)
#colSums(is.na(airquality))
median(airquality$Ozone,na.rm=TRUE)
## [1] 31.5
air<-airquality
air$Ozone<- ifelse(is.na(airquality$Ozone),31.5,airquality$Ozone)
# 오답: air$Ozone<- ifelse(airquality$Ozone==NA,31.5,airquality$Ozone)
mean(air$Ozone)
## [1] 39.55882
#5 diamonds 데이터셋에서 price 최댓값
library(ggplot2)
#glimpse(diamonds)
#colSums(is.na(diamonds))
max(diamonds$price)
## [1] 18823
#6 cut,color 범주별로 price 평균 구하고, price 내림차순으로 상위 3개 추출
di<-diamonds
#오답: di %>% group_by(cut,color) %>% mean(price)
di %>% group_by(cut,color) %>% summarize(m=mean(price)) %>%
arrange(desc(m)) %>% head(3)
## `summarise()` has grouped output by 'cut'. You can override using the `.groups`
## argument.
## # A tibble: 3 × 3
## # Groups: cut [2]
## cut color m
## <ord> <ord> <dbl>
## 1 Premium J 6295.
## 2 Premium I 5946.
## 3 Very Good I 5256.
#7 컬럼cut에서 Ideal의 백분율 구해라
di %>% group_by(cut) %>% summarize(n=n()) %>%
mutate(total=sum(n),pct=n/total*100)
## # A tibble: 5 × 4
## cut n total pct
## <ord> <int> <int> <dbl>
## 1 Fair 1610 53940 2.98
## 2 Good 4906 53940 9.10
## 3 Very Good 12082 53940 22.4
## 4 Premium 13791 53940 25.6
## 5 Ideal 21551 53940 40.0
#8 Europe과 Africa 대륙 중 가장 많은 인구(pop)을 가졌던 국가와 년도 구해라
#install.packages("gapminder")
library(gapminder)
#glimpse(gapminder)
gap<-gapminder
gap1<-gap %>% filter(gap$continent=="Europe"|gap$continent=="Africa")
gap1 %>% filter(pop==max(pop))
## # A tibble: 1 × 6
## country continent year lifeExp pop gdpPercap
## <fct> <fct> <int> <dbl> <int> <dbl>
## 1 Nigeria Africa 2007 46.9 135031164 2014.