我想根据数据框每行的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
不重塑的情况下做到这一点?
一个选项是pmap
frompurrr
循环遍历starts_with
'q_'列的行,通过sort
按decreasing
顺序ing 行,获得第一个 'n' 排序的元素head
和sum
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
或使用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
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句