【问题标题】:Safest and most efficient way to do a conditional mutate with dplyr使用 dplyr 进行条件变异的最安全和最有效的方法
【发布时间】:2021-04-26 07:41:02
【问题描述】:

我想知道在不从数据框中删除数据的情况下,将 mutate 应用于数据子集的最佳方法是什么。例如,我想计算范围为-5:5 的数组的正整数的平均值。我的做法是:

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

对此有何看法?有没有一种“更整洁”的方式来做到这一点?提前致谢!

【问题讨论】:

  • 我确信这是一个非常高效且整洁的解决方案。你能详细说明它应该在什么意义上更高效或更整洁吗?
  • 我不确定[mutate 中的这种行为是故意的还是将来可能不起作用的“副作用”。我想知道是否有办法使用主要的dplyr 动词。
  • 就我而言,这绝对是故意的,我看不到这种情况将来会消失。

标签: r filter dplyr


【解决方案1】:

总的来说,如果这是你想要的,你所拥有的看起来不错。如果您只想要一个号码,您可以使用filtersummarize

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

# 3

如果你愿意,你也可以使用group_by,但这也会给你非正值的平均值:

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  

【讨论】:

    猜你喜欢
    • 2014-04-15
    • 2018-06-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多