df <- mtcars
prop <- df %>%
group_by(cyl, .drop = FALSE) %>%
filter(rowMeans(is.na(across(c(disp, drat, wt)))) <= 0.5) %>%
summarise(N = n(), across(c(disp, drat, wt, qsec, vs), ~mean(. == 1, na.rm=TRUE))) %>%
select(disp, drat, wt, qsec, vs)
是否有一种方法可以在外部向量上运行filter()
,summarise()
和select()
,如:
select1 <- df %>% select(disp, drat, wt)
select2 <- df %>% select(disp, drat, wt, qsec, vs)
而不是每次都定义各自的变量来减少对错误的敏感性?
例如,summarise(N = n(), across(all_of(select2)), ~mean(. == 1, na.rm=TRUE)) %>%
给了我一个错误。
谢谢!
使用!!
from{rlang}
library(rlang)
library(dplyr)
df <- mtcars
select1 <- df %>% select(disp, drat, wt) %>% names()
select2 <- df %>% select(disp, drat, wt, qsec, vs) %>% names()
df %>%
group_by(cyl, .drop = FALSE) %>%
filter(rowMeans(is.na(across(!!select1))) <= 0.5) %>%
summarise(N = n(), across(!!select2, ~ mean(. == 1, na.rm = TRUE))) %>%
select(!!select2)
#> # A tibble: 3 × 5
#> disp drat wt qsec vs
#> <dbl> <dbl> <dbl> <dbl> <dbl>
#> 1 0 0 0 0 0.909
#> 2 0 0 0 0 0.571
#> 3 0 0 0 0 0
由reprex包(v2.0.1)在2022-07-12创建