dplyr `across()`函数需要`rowwise()`函数是吗?

问题描述 投票:0回答:1
packageVersion("dplyr")
#[1] ‘0.8.99.9002’

请注意 这道题使用了dplyr的新的方法。across() 功能。要安装最新的dplyr开发版,请使用以下命令 remotes::install_github("tidyverse/dplyr") 命令。要恢复到已发布的dplyr版本,请执行以下命令 install.packages("dplyr") 命令。如果你在未来的某个时间点读到这篇文章,并且已经在使用dplyr 1.X+,你就不需要担心这个注释了。

library(tidyverse)
WorldPhones %>% 
  as.data.frame() %>% 
  rowwise() %>% 
  mutate(mean = mean(c_across(N.Amer:Mid.Amer), na.rm = TRUE))
#> # A tibble: 7 x 8
#> # Rowwise: 
#>   N.Amer Europe  Asia S.Amer Oceania Africa Mid.Amer   mean
#>    <dbl>  <dbl> <dbl>  <dbl>   <dbl>  <dbl>    <dbl>  <dbl>
#> 1  45939  21574  2876   1815    1646     89      555 10642 
#> 2  60423  29990  4708   2568    2366   1411      733 14600.
#> 3  64721  32510  5230   2695    2526   1546      773 15714.
#> 4  68484  35218  6662   2845    2691   1663      836 16914.
#> 5  71799  37598  6856   3000    2868   1769      911 17829.
#> 6  76036  40341  8220   3145    3054   1905     1008 19101.
#> 7  79831  43173  9053   3338    3224   2005     1076 20243.

本文由Keith McNulty博士撰写 提供了一个很好的例子(如上图所示),使用dplyr的新的 c_across() 函数。你穿过每一行,R计算所选列间的平均值。

让我们用mtcars数据框架做同样的事情,而不是选择每行跨列的最大值。我们将只选择 "drat "和 "wt "变量,以保持简单。

mtcars %>% 
  select(drat, wt) %>% 
  as_tibble() %>% 
  mutate(max = max(c_across(drat:wt), na.rm = TRUE))
#> # A tibble: 32 x 3
#>     drat    wt   max
#>    <dbl> <dbl> <dbl>
#>  1  3.9   2.62  5.42
#>  2  3.9   2.88  5.42
#>  3  3.85  2.32  5.42
#>  4  3.08  3.22  5.42
#>  5  3.15  3.44  5.42
#>  6  2.76  3.46  5.42
#>  7  3.21  3.57  5.42
#>  8  3.69  3.19  5.42
#>  9  3.92  3.15  5.42
#> 10  3.92  3.44  5.42
#> # ... with 22 more rows

为什么dplyr不选择每行的最大值,然后显示在 max 栏?我想要的会是这样的。

#> # A tibble: 32 x 3
#>     drat    wt   max 
#>    <dbl> <dbl> <dbl>
#>  1  3.9   2.62   3.9
#>  2  3.9   2.88   3.9
#>  3  3.85  2.32  3.85
#>  4  3.08  3.22  3.22
#>  5  3.15  3.44  3.44
#>  6  2.76  3.46  3.46
#>  7  3.21  3.57  3.57
#>  8  3.69  3.19  3.69
#>  9  3.92  3.15  3.92
#> 10  3.92  3.44  3.92
#> # ... with 22 more rows

我怎样才能做到这一点?c_across 在Worldphones上能用,但在MTCars上不能用。我们将 "工作 "定义为 "做我想要的事情"。

r dplyr max
1个回答
2
投票

你没有 rowwise 部分。记住 c_across 只对行操作有效(这是你现在想要的)。

mtcars %>% 
    select(drat, wt) %>% 
    rowwise() %>% 
    mutate(max = max(c_across(drat:wt), na.rm = TRUE))

# A tibble: 32 x 3
# Rowwise: 
    drat    wt   max
   <dbl> <dbl> <dbl>
 1  3.9   2.62  3.9 
 2  3.9   2.88  3.9 
 3  3.85  2.32  3.85
 4  3.08  3.22  3.22
 5  3.15  3.44  3.44
 6  2.76  3.46  3.46
 7  3.21  3.57  3.57
 8  3.69  3.19  3.69
 9  3.92  3.15  3.92
10  3.92  3.44  3.92
# ... with 22 more rows
© www.soinside.com 2019 - 2024. All rights reserved.