summarise
這周介紹最后一個動詞 summarise
該函數并沒有什么實質性功能宝踪,我的理解就是相當于apply類的函數,對數據集進行包裝函數處理瘩燥,即數據集的函數放在summarise里面秕重。要想體現(xiàn)出該函數的優(yōu)勢溶耘,要和group_by函數聯(lián)合使用
group_by函數:是對數據集進行分組處理
by_day <- group_by(flights, year, month, day)表示先按照年,再按照月服鹅,最后按照日來排序
summarise(by_day, delay = mean(dep_delay, na.rm = TRUE))
就得到下面結果
管道工具 %>%
%>% R里面表示數據的傳遞
例如:
by_dest <- group_by(flights, dest)
delay <- summarise(by_dest, count = n(), dist = mean(distance, na.rm = TRUE), delay = mean(arr_delay, na.rm = TRUE))
delay <- filter(delay, count > 20, dest != "HNL")
如果我們使用管道工具,就是下面這樣
delays <- flights %>%
group_by(dest) %>%
summarise( count = n(), dist = mean(distance, na.rm = TRUE), delay = mean(arr_delay, na.rm = TRUE) ) %>%
filter(count > 20, dest != "HNL")最初的數據源是flights 企软,則就開始從數據源開始進行向下延伸
挑出不含缺失值的小技巧
!is.na()
例如挑選 dep_delay這一列不含缺失值
not_cancelled <- flights %>% filter(!is.na(dep_delay))
挑出兩列不含缺失值的列
not_cancelled <- flights %>% filter(!is.na(dep_delay), !is.na(arr_delay))
管道操作符仗哨,來畫圖
delays <- not_cancelled %>%
group_by(tailnum) %>%
summarise( delay = mean(arr_delay) )
ggplot(data = delays, mapping = aes(x = delay)) + geom_freqpoly(binwidth = 10)
delays <- not_cancelled %>%
group_by(tailnum) %>%
summarise( delay = mean(arr_delay) )%>%
ggplot(mapping = aes(x = delay)) + geom_freqpoly(binwidth = 10)
image
summarize里面還有一些常見的函數
median(x) 中位數
min(x) 最值
quantile(x, 0.25) 下四分位數
max(x) 最值
sd(x), 方差
IQR(x) 四分位差
mad(x) 平均絕對離差
總結
至此,dplyr包的函數萨醒,我們今天就講解完畢,下面我們總結一下幾大函數
filter 是對行的篩選
select 是對列的篩選
mutate 是產生新的變量
arrange 是排序 (desc 表倒序)
summarise 是函數總結 里面內置了像mean等常見的函數