Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
3.5k views
in Technique[技术] by (71.8m points)

r - Safest and most efficient way to do a conditional mutate with dplyr

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!


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Overall, what you have looks fine if that's what you want. If you just wanted a single number you could use the filter and summarize:

tibble(x = -5:5) %>% 
  dplyr::filter(x > 0) %>% 
  dplyr::summarize(mean = mean(x))

# 3

You could also do group_by if you wanted, but this would give you the average of non-positive values too:

tibble(x = -5:5) %>% 
  dplyr::group_by(group = x > 0) %>% 
  dplyr::mutate(mean = mean(x)) %>% 
  dplyr::ungroup() %>% 
  dplyr::select(-group) 

# A tibble: 11 x 2
       x  mean
   <int> <dbl>
 1    -5  -2.5
 2    -4  -2.5
 3    -3  -2.5
 4    -2  -2.5
 5    -1  -2.5
 6     0  -2.5
 7     1   3  
 8     2   3  
 9     3   3  
10     4   3  
11     5   3  

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...