I wonder what is the best way to apply mutate to a subset of the data, without removing data from the dataframe. For instance, I would like to calculate the mean of positive integers of an array ranging from -5:5
. The way I do it is:
library(dplyr)
#>
#> Attache Paket: 'dplyr'
#> The following objects are masked from 'package:stats':
#>
#> filter, lag
#> The following objects are masked from 'package:base':
#>
#> intersect, setdiff, setequal, union
tibble(x = -5:5) %>%
mutate(positive_mean = mean(x[x>0]))
#> # A tibble: 11 x 2
#> x positive_mean
#> <int> <dbl>
#> 1 -5 3
#> 2 -4 3
#> 3 -3 3
#> 4 -2 3
#> 5 -1 3
#> 6 0 3
#> 7 1 3
#> 8 2 3
#> 9 3 3
#> 10 4 3
#> 11 5 3
Any opinion on this? Is there a "tidier" way to do this? Thanks in advance!
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…