r语言 - 迭代dplyr:: summary中的值和变量名



我使用以下脚本在R中制作一个表:

library(dplyr)
library(tidyr)
get_probability <- function(parameter_array, threshold) {
return(round(100 * sum(parameter_array >= threshold) /
length(parameter_array)))
}
thresholds = c(75, 100, 125)
mtcars %>% group_by(gear) %>%
dplyr::summarise(
low=get_probability(disp, thresholds[[1]]),
medium=get_probability(disp, thresholds[[2]]),
high=get_probability(disp, thresholds[[3]]),
)

显示的表如下:

# A tibble: 3 x 4
gear   low medium  high
<dbl> <dbl>  <dbl> <dbl>
1     3   100    100    93
2     4    92     67    50
3     5   100     80    60

我的问题是,如何将我传递给summarise的内容浓缩为一行?即,是否有一种方法来迭代这两个thresholds向量,同时传递自定义变量名称?

dplyr的最新版本中,summarise将自动拼接在其内部创建的数据帧到新的列中。因此,您只需要一种方法来迭代阈值以创建data.frame。一个选项是purrr:::map_dfc

library(dplyr, warn.conflicts = FALSE)
get_probability <- function(parameter_array, threshold) {
return(round(100 * sum(parameter_array >= threshold) /
length(parameter_array)))
}
thresholds = c(75, 100, 125)
thresholds <- setNames(thresholds, c('low', 'medium', 'high'))
mtcars %>% 
group_by(gear) %>% 
summarise(purrr::map_dfc(thresholds, ~ get_probability(disp, .x)))
#> # A tibble: 3 × 4
#>    gear   low medium  high
#>   <dbl> <dbl>  <dbl> <dbl>
#> 1     3   100    100    93
#> 2     4    92     67    50
#> 3     5   100     80    60

如果您不想使用额外的包,您可以只使用lapply,然后将输出转换为data.frame。(将旧版本R中的(x)替换为function(x))

mtcars %>% 
group_by(gear) %>% 
summarise(as.data.frame(lapply(thresholds, (x) get_probability(disp, x))))
#> # A tibble: 3 × 4
#>    gear   low medium  high
#>   <dbl> <dbl>  <dbl> <dbl>
#> 1     3   100    100    93
#> 2     4    92     67    50
#> 3     5   100     80    60

由reprex包(v2.0.1)在2021-08-17创建

最新更新