![](/img/trans.png)
[英]How to apply an anonymous function inside dplyr mutate pipeline in a rowwise manor?
[英]How to apply a window function over a subset of rows inside dplyr::mutate?
讓我們假設mtcars
是一個有序的 data.frame 並且我想要前幾行的最大值。 然后,我可以這樣做:
> mtcars %>% mutate(test = cummax(wt))
mpg cyl disp hp drat wt qsec vs am gear carb test
1 21.0 6 160.0 110 3.90 2.620 16.46 0 1 4 4 2.620
2 21.0 6 160.0 110 3.90 2.875 17.02 0 1 4 4 2.875
3 22.8 4 108.0 93 3.85 2.320 18.61 1 1 4 1 2.875
4 21.4 6 258.0 110 3.08 3.215 19.44 1 0 3 1 3.215
5 18.7 8 360.0 175 3.15 3.440 17.02 0 0 3 2 3.440
6 18.1 6 225.0 105 2.76 3.460 20.22 1 0 3 1 3.460
7 14.3 8 360.0 245 3.21 3.570 15.84 0 0 3 4 3.570
8 24.4 4 146.7 62 3.69 3.190 20.00 1 0 4 2 3.570
9 22.8 4 140.8 95 3.92 3.150 22.90 1 0 4 2 3.570
10 19.2 6 167.6 123 3.92 3.440 18.30 1 0 4 4 3.570
11 17.8 6 167.6 123 3.92 3.440 18.90 1 0 4 4 3.570
12 16.4 8 275.8 180 3.07 4.070 17.40 0 0 3 3 4.070
13 17.3 8 275.8 180 3.07 3.730 17.60 0 0 3 3 4.070
14 15.2 8 275.8 180 3.07 3.780 18.00 0 0 3 3 4.070
15 10.4 8 472.0 205 2.93 5.250 17.98 0 0 3 4 5.250
16 10.4 8 460.0 215 3.00 5.424 17.82 0 0 3 4 5.424
17 14.7 8 440.0 230 3.23 5.345 17.42 0 0 3 4 5.424
...
現在我想獲得最大值,不僅是所有前面的行,而且只是wt < 4
的前面的行,所以如果下一個,我會從test2
的第 12 行得到不同的結果(在下面的test2
列中表示)指令有效:
> mtcars %>% mutate(test = cummax(wt), test2 = cummax(wt[wt < 4]))
mpg cyl disp hp drat wt qsec vs am gear carb test test2
1 21.0 6 160.0 110 3.90 2.620 16.46 0 1 4 4 2.620 2.620
2 21.0 6 160.0 110 3.90 2.875 17.02 0 1 4 4 2.875 2.875
3 22.8 4 108.0 93 3.85 2.320 18.61 1 1 4 1 2.875 2.875
4 21.4 6 258.0 110 3.08 3.215 19.44 1 0 3 1 3.215 3.215
5 18.7 8 360.0 175 3.15 3.440 17.02 0 0 3 2 3.440 3.440
6 18.1 6 225.0 105 2.76 3.460 20.22 1 0 3 1 3.460 3.460
7 14.3 8 360.0 245 3.21 3.570 15.84 0 0 3 4 3.570 3.570
8 24.4 4 146.7 62 3.69 3.190 20.00 1 0 4 2 3.570 3.570
9 22.8 4 140.8 95 3.92 3.150 22.90 1 0 4 2 3.570 3.570
10 19.2 6 167.6 123 3.92 3.440 18.30 1 0 4 4 3.570 3.570
11 17.8 6 167.6 123 3.92 3.440 18.90 1 0 4 4 3.570 3.570
12 16.4 8 275.8 180 3.07 4.070 17.40 0 0 3 3 4.070 3.570
13 17.3 8 275.8 180 3.07 3.730 17.60 0 0 3 3 4.070 3.730
14 15.2 8 275.8 180 3.07 3.780 18.00 0 0 3 3 4.070 3.780
15 10.4 8 472.0 205 2.93 5.250 17.98 0 0 3 4 5.250 3.780
16 10.4 8 460.0 215 3.00 5.424 17.82 0 0 3 4 5.424 3.780
17 14.7 8 440.0 230 3.23 5.345 17.42 0 0 3 4 5.424 3.780
...
但實際上,該指令會產生錯誤:
> mtcars %>% mutate(test = cummax(wt[wt<4]))
Error: Column `test` must be length 32 (the number of rows) or one, not 28
讓我補充一點,我想按組執行此操作,因此指令將從mtcars %>% group_by(cyl) %>%...
我能怎么做?
先感謝您!
我會使用ifelse
,並用 -Inf 替換任何違反您條件的-Inf
mtcars %>%
mutate(test = cummax(ifelse(wt < 4, wt, -Inf)))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.