group_by的用處將選擇的欄位變量分組,可以單獨使用,但更多的是結合其他函數(select、filter、summaise、mutate)進行計算輸出,通常都是與summarise進行統計的計算,要注意的是進行分組統計時,最好先將欄位的型態、錯誤數值調整好,才不會出來的結果不盡理想。
基本語法
group_by(dataset, 想分組的欄位變量..)
先來創建一個基本的tibble進行演示
# 創建一個tibble存入數值
num_df <- tibble(
    number = c(1, 2, -1, 5, 8, 9),
    letter = c("a", "b", "c", "a", "c", "a")
)
# 輸出結果
r$> num_df
# A tibble: 6 x 2
  number letter
   <dbl> <chr> 
1      1 a     
2      2 b     
3     -1 c     
4      5 a     
5      8 c
6      9 a
先進行基本的分組試試看,沒有設定分組後的計算方式,出來的結果也沒有甚麼變化
# 將letter分組
group_by(num_df, letter)
# 輸出結果
r$> group_by(num_df, letter)
# A tibble: 6 x 2
# Groups:   letter [3]
  number letter       
   <dbl> <chr> 
1      1 a     
2      2 b     
3     -1 c     
4      5 a     
5      8 c     
6      9 a   
加入通道與summarise計算各個字母對應的平均值,a(1 + 5 + 8) / 3 >> 5,b(2) / 1 >> 2,c(-1 + 8) / 2 >> 3.5
# 將letter分組後計算平均值
num_df <- group_by(num_df, letter) %>% 
    summarise(
        number = mean(number)
        )
# 輸出結果
r$> num_df
# A tibble: 3 x 2
  letter number
  <chr>   <dbl>
1 a         5  
2 b         2  
3 c         3.5
添加filter過濾會有比較特殊的情況要小心使用,分組完成後再進行過濾或者分組與過濾一同進行會產生不同的結果。
# 將letter分組存入變量
num_df_v1 <- group_by(num_df, letter)
# 將分組完成的變量進行篩選
num_df_v1 <- filter(num_df_v1, number < 1)
# 輸出結果
r$> num_df_v1
# A tibble: 1 x 2
# Groups:   letter [1]
  number letter
   <dbl> <chr>
1     -1 c
# 加上pipes直接計算
num_df_v2 <- num_df %>% 
    group_by(letter) %>% 
    filter(
        number < -1
    )
# 輸出結果 >> 數值是空的
r$> num_df_v2
# A tibble: 0 x 2
# Groups:   letter [0]
# ... with 2 variables: number <dbl>, letter <chr>
至於配合mutate使用上來說,分開使用或是結合pipes都沒有filter的狀況
# 將letter分組存入變量
num_df_v1 <- group_by(num_df, letter)
# 將分組完成的變量搭配mutate
num_df_v1 <- mutate(num_df_v1, new_number = mean(number))
# 輸出結果
r$> num_df_v1
# A tibble: 6 x 3
# Groups:   letter [3]    
  number letter new_number
   <dbl> <chr>       <dbl>
1      1 a             5  
2      2 b             2  
3     -1 c             3.5
4      5 a             5
5      8 c             3.5
6      9 a             5
# 加上pipes直接計算
num_df_v2 <- num_df %>% 
    group_by(letter) %>% 
    mutate(new_number = mean(number))
# 輸出結果
r$> num_df_v2
# A tibble: 6 x 3
# Groups:   letter [3]    
  number letter new_number
   <dbl> <chr>       <dbl>
1      1 a             5  
2      2 b             2  
3     -1 c             3.5
4      5 a             5
5      8 c             3.5
6      9 a             5

 
沒有留言:
張貼留言