dplyr 常用函數 [mutate]


https://r4ds.had.co.nz/transform.html#add-new-variables-with-mutate

5.mutate可根據已有的變量添加新的變量

變形函數mutate

除了提取已有列,根據已有的列添加新的列也很常見。mutate()具有此功能
mutate()總會添加新的列到已有列的末尾。為了方便查看數據的變化,在Rstudio中可通過View()實現。

library(nycflights13)
library(tidyverse)

flights_sml <- select(flights, 
  year:day, 
  ends_with("delay"), 
  distance, 
  air_time
)
mutate(flights_sml,
  gain = dep_delay - arr_delay,
  speed = distance / air_time * 60
)
#> # A tibble: 336,776 x 9
#>    year month   day dep_delay arr_delay distance air_time  gain speed
#>   <int> <int> <int>     <dbl>     <dbl>    <dbl>    <dbl> <dbl> <dbl>
#> 1  2013     1     1         2        11     1400      227    -9  370.
#> 2  2013     1     1         4        20     1416      227   -16  374.
#> 3  2013     1     1         2        33     1089      160   -31  408.
#> 4  2013     1     1        -1       -18     1576      183    17  517.
#> 5  2013     1     1        -6       -25      762      116    19  394.
#> 6  2013     1     1        -4        12      719      150   -16  288.
#> # … with 3.368e+05 more rows

隨后,可以使用剛剛添加的列:

mutate(flights_sml,
  gain = dep_delay - arr_delay,
  hours = air_time / 60,
  gain_per_hour = gain / hours
)

如果僅希望保留新添加的變量,通過transmute()實現:

transmute(flights,
  gain = dep_delay - arr_delay,
  hours = air_time / 60,
  gain_per_hour = gain / hours
)
#> # A tibble: 336,776 x 3
#>    gain hours gain_per_hour
#>   <dbl> <dbl>         <dbl>
#> 1    -9  3.78         -2.38
#> 2   -16  3.78         -4.23
#> 3   -31  2.67        -11.6 
#> 4    17  3.05          5.57
#> 5    19  1.93          9.83
#> 6   -16  2.5          -6.4 
#> # … with 3.368e+05 more rows

5.1 創建函數

通過mutate()添加新變量可以很多功能,而這些創建的函數都必須是矢量化的,即:必須是向量值作為輸入,返回相同數目值的一個向量。沒有辦法列出所有可能使用的函數,但列出了常用的功能:

  • 算法操作符:+-*……。這些都是使用所謂的“回收規則”進行矢量化的。如果某個參數比其他的要短,這個短的參數會被延伸至相同長度。當參數之一是單個數字時非常有用:air_time / 60hours * 60 + minute等。
    算法操作符在使用整合函數時同樣有用。例如,x / sum(x)
  • 模運算:%/%(整數除法)和%%(余數),其中x == y *(x%/%y) + (x %% y)。 模運算允許您將整數分解成碎片。 例如,在航班數據集中,可以根據dep_time的計算hourminute
transmute(flights,
  dep_time,
  hour = dep_time %/% 100,
  minute = dep_time %% 100
)
#> # A tibble: 336,776 x 3
#>   dep_time  hour minute
#>      <int> <dbl>  <dbl>
#> 1      517     5     17
#> 2      533     5     33
#> 3      542     5     42
#> 4      544     5     44
#> 5      554     5     54
#> 6      554     5     54
#> # … with 3.368e+05 more rows
  • Logs:log(),log2(),log10().對數在處理跨越多個數量級的數據時是非常有用的轉換。它們還將乘法關系轉換為加法,這是建模中回歸的一個特征。
    在其他條件相同的情況下,建議使用log2(),因為它很容易解釋:對數刻度上的1對應於原始刻度上的倍增,-1的差異對應於減半。
  • Offsets:lead()lag()允許引用前導或滯后值。 這允許計算運行差異(例如x - lag(x))或查找值何時更改(x!= lag(x))。 它們與group_by()一起使用最為有用。
(x <- 1:10)
#>  [1]  1  2  3  4  5  6  7  8  9 10
lag(x)
#>  [1] NA  1  2  3  4  5  6  7  8  9
lead(x)
#>  [1]  2  3  4  5  6  7  8  9 10 NA
  • 累積和滾動聚合:R提供運行總和,產品(我暫時也不知道),最小和最大值的函數:cumsum()cumprod()cummin()cummax(); 和dplyr提供累積均值的cummean()。 如果需要滾動聚合(即通過滾動窗口計算的總和),請使用RcppRoll包。
x
#>  [1]  1  2  3  4  5  6  7  8  9 10
cumsum(x)
#>  [1]  1  3  6 10 15 21 28 36 45 55
cummean(x)
#>  [1] 1.0 1.5 2.0 2.5 3.0 3.5 4.0 4.5 5.0 5.5
  • 邏輯比較:<<=>>=!===如果正在執行復雜的邏輯運算序列,那么將臨時值存儲在新變量中通常是個好主意,這樣就可以檢查每個步驟是否按預期工作
  • 排名:有許多排名函數,但應該從min_rank()開始。 它執行最常見的排名類型(例如,1st, 2nd, 2nd, 4th)。 默認值為小等級的最小值;使用desc(x)給出最大值最小的等級。
y <- c(1, 2, 2, NA, 3, 4)
min_rank(y)
#> [1]  1  2  2 NA  4  5
min_rank(desc(y))
#> [1]  5  3  3 NA  2  1

如果min_rank不是所需的,可通過row_number() dense_rank()percent_rank()cume_dist()ntile()查詢。

row_number(y)
#> [1]  1  2  3 NA  4  5
dense_rank(y)
#> [1]  1  2  2 NA  3  4
percent_rank(y)
#> [1] 0.00 0.25 0.25   NA 0.75 1.00
cume_dist(y)
#> [1] 0.2 0.6 0.6  NA 0.8 1.0

5.5.2 練習

1. Currently dep_time and sched_dep_time are convenient to look at, but hard to compute with because they’re not really continuous numbers. Convert them to a more convenient representation of number of minutes since midnight.

2. Compare air_time with arr_time - dep_time. What do you expect to see? What do you see? What do you need to do to fix it?

3. Compare dep_time, sched_dep_time, and dep_delay. How would you expect those three numbers to be related?

4. Find the 10 most delayed flights using a ranking function. How do you want to handle ties? Carefully read the documentation for min_rank().

5. What does 1:3 + 1:10 return? Why?

6. What trigonometric functions does R provide?


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM