【问题标题】:Is there a way to use rowwise to get means across rows the correct way?有没有办法使用 rowwise 以正确的方式跨行获取平均值?
【发布时间】:2021-10-07 07:51:06
【问题描述】:

我不确定我是否完全理解了 dplyr 中的 rowwise 函数。我似乎得到了预期的结果。下面是代码和预期的结果。

library(dplyr)

set.seed(123)

mydf <- tibble(
  a1 = floor(rnorm(10, 5, 2)),
  a2 = floor(rnorm(10, 6, 3)),
  a3 = floor(rnorm(10, 8, 3))
)

mydf %>%
  rowwise() %>%
  mutate(allmeanrow = mean(a1:a3))

# Expected
mydf %>%
  mutate(allmeanrow = rowMeans(.))

【问题讨论】:

    标签: r dplyr rowwise


    【解决方案1】:

    您需要将您的列包装成c_across

    mydf %>%
      rowwise() %>%
      mutate(allmeanrow = mean(c_across(a1:a3))) %>%
      ungroup()
    

    给出:

    # A tibble: 10 x 4
    # Rowwise: 
          a1    a2    a3 allmeanrow
       <dbl> <dbl> <dbl>      <dbl>
     1     3     9     4       5.33
     2     4     7     7       6   
     3     8     7     4       6.33
     4     5     6     5       5.33
     5     5     4     6       5   
     6     8    11     2       7   
     7     5     7    10       7.33
     8     2     0     8       3.33
     9     3     8     4       5   
    10     4     4    11       6.33
    

    注意,我总是在按行操作后取消分组,因为按行对数据按行分组,所以任何后续操作仍将按行执行。

    参见此处:https://dplyr.tidyverse.org/articles/rowwise.html

    【讨论】:

      【解决方案2】:

      我们可以使用pmap,它比rowwise 更有效。只需遍历数据 (cur_data()),将行值捕获为向量 (c(...)) 并获取 mean

      library(purrr)
      library(dplyr)
      mydf %>% 
          mutate(allmeanrow = pmap_dbl(cur_data(), ~ mean(c(...))))
      # A tibble: 10 × 4
            a1    a2    a3 allmeanrow
         <dbl> <dbl> <dbl>      <dbl>
       1     3     9     4       5.33
       2     4     7     7       6   
       3     8     7     4       6.33
       4     5     6     5       5.33
       5     5     4     6       5   
       6     8    11     2       7   
       7     5     7    10       7.33
       8     2     0     8       3.33
       9     3     8     4       5   
      10     4     4    11       6.33
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2018-08-13
        • 2014-12-17
        • 2019-09-22
        • 1970-01-01
        • 2021-08-23
        • 2014-10-26
        • 2014-04-09
        相关资源
        最近更新 更多