dplyr::summarize_at-按传递的变量顺序排序列,然后按应用的函数顺序排序。

4

问题

我想使用dplyr::summarize_at()(或等效方法)获得一个摘要表格,其中列首先按使用的分组变量(G)顺序排序,然后按传递的变量(V)顺序排序,最后按应用的函数(F)顺序排序。默认顺序首先由G确定,然后由F确定,最后由V确定。

示例

代码:

library(purrr)
library(dplyr)

q025 <- partial(quantile, probs  = 0.025, na.rm = TRUE)
q975 <- partial(quantile, probs  = 0.975, na.rm = TRUE)

vars_to_summarize <- c("height", "mass")

my_summary <- starwars %>% 
    filter(skin_color  %in% c("gold", "green")) %>% 
    group_by(skin_color) %>% 
    summarise_at(vars_to_summarize, funs(q025, mean, q975))

结果为:

my_summary
## A tibble: 2 x 7
##   skin_color height_q025 mass_q025 height_mean mass_mean height_q975 mass_q975
##        <chr>       <dbl>     <dbl>       <dbl>     <dbl>       <dbl>     <dbl>
## 1       gold     167.000      75.0         167        75      167.00      75.0
## 2      green      79.375      22.7         169        NA      204.75     110.4

所需变量的顺序应该是:

skin_color, height_q025, height_mean, height_q975, mass_q025, mass_mean, mass_q975

我希望使用类似于这个(简单的)代码:

我想使用下面这段(naively simple)代码:

my_summary  %>% 
    select(everything(), starts_with(vars_to_summarize))

但是它没有发挥作用。即使是这段代码也没有像我预期的那样工作(尽管它不是我想要的通用解决方案):
my_summary  %>% 
    select(everything(),
           starts_with(vars_to_summarize[1]),
           starts_with(vars_to_summarize[2]))

最好将everything()函数放在select()函数的最后一个参数。

概括来说

比如,我有:

  1. N个分组变量("gr_"),它们通过group_by()传递,
  2. L个需要汇总的变量("var_"),和
  3. M个汇总函数("fun_")需要应用。

通常情况下,在汇总表中变量的期望顺序应该遵循以下模式:

gr_1, gr_2, ..., gr_N,   
var_1_fun_1, var_1_fun_2, ..., var_1_fun_M,  
var_2_fun_1, var_2_fun_2, ..., var_2_fun_M, 
...,
var_L_fun_1, var_L_fun_2, ..., var_L_fun_M

1
尝试使用 my_summary %>% select(c(matches(vars_to_summarize[1]), matches(vars_to_summarize[2]))) - akrun
1个回答

4
我们可以使用 matchesgrep
my_summary %>%
    select(grep(paste(vars_to_summarize, collapse="|"), names(.), invert = TRUE), 
           matches(vars_to_summarize[1]),
           matches(vars_to_summarize[2]))
# A tibble: 2 x 7
#    skin_color height_q025 height_mean height_q975 mass_q025 mass_mean mass_q975
#       <chr>       <dbl>       <dbl>       <dbl>     <dbl>     <dbl>     <dbl>
#1       gold     167.000         167      167.00      75.0        75      75.0
#2      green      79.375         169      204.75      22.7        NA     110.4

如果有许多列,另一种选择是从列名中删除下划线(“_”)子字符串,将其与“vars_to_summarize”匹配,并在“select”内进行排序。
my_summary %>% 
   select(order(match(sub("_.*", "", names(.)), vars_to_summarize, nomatch = 0)))
# A tibble: 2 x 7
#    skin_color height_q025 height_mean height_q975 mass_q025 mass_mean mass_q975
#       <chr>       <dbl>       <dbl>       <dbl>     <dbl>     <dbl>     <dbl>
#1       gold     167.000         167      167.00      75.0        75      75.0
#2      green      79.375         169      204.75      22.7        NA     110.4

1
太棒了!!☺ 就像我打算拥有包含 _ 的变量名称一样,正则表达式 sub("(.*)_.*?$", "\\1", names(.)) 更为合适。 - GegznaV

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接