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

尼古拉斯

我想根据数据框每行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)

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

阿克伦

一个选项是pmapfrompurrr循环遍历starts_with'q_'列的行,通过sortdecreasing顺序ing 行,获得第一个 'n' 排序的元素headsum

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))))

-输出

# 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

或使用rowwisedplyr.

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

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章