如何使用dplyr按行求和n个最高值而不重塑?

nic*_*las 6 r dplyr

我想根据数据框每行的n 个最高值创建一个新列。

以下面的例子为例:

library(tibble)
df <- tribble(~name, ~q_1, ~q_2, ~q_3, ~sum_top_2,
              "a", 4, 1, 5, 9,
              "b", 2, 8, 9, 17)
Run Code Online (Sandbox Code Playgroud)

这里,sum_top_2列对以“ q_ ”为前缀的列的 2 个最高值求和。我想按行概括为n 个最高值。我如何在dplyr不重塑的情况下做到这一点?

akr*_*run 4

一个选项是pmapfrom循环遍历“q_”purrr列的行,通过按顺序 ing 行,使用and获取前“n”个排序元素starts_withsortdecreasingheadsum

library(dplyr)
library(purrr)
library(stringr)
n <- 2
df %>% 
   mutate(!! str_c("sum_top_", n) := pmap_dbl(select(cur_data(), 
           starts_with('q_')), 
            ~ sum(head(sort(c(...), decreasing = TRUE), n))))
Run Code Online (Sandbox Code Playgroud)

-输出

# A tibble: 2 x 5
  name    q_1   q_2   q_3 sum_top_2
  <chr> <dbl> <dbl> <dbl>     <dbl>
1 a         4     1     5         9
2 b         2     8     9        17
Run Code Online (Sandbox Code Playgroud)

或者使用rowwise来自dplyr.

df %>% 
   rowwise %>% 
   mutate(!! str_c("sum_top_", n) := sum(head(sort(c_across(starts_with("q_")), 
           decreasing = TRUE), n))) %>% 
   ungroup
# A tibble: 2 x 5
  name    q_1   q_2   q_3 sum_top_2
  <chr> <dbl> <dbl> <dbl>     <dbl>
1 a         4     1     5         9
2 b         2     8     9        17
Run Code Online (Sandbox Code Playgroud)