我正在创建一个计算“运行”次数或丢失或完整数据的函数 - 我希望它可以使用dplyr::group_by
,所以我将其编写为 S3 方法 - 下面是此代码的简化示例。
不幸的是,我发现裸露的未加引号的变量名不起作用,但引用它,这确实有效,很奇怪。
下面是输出示例
fun_run <- function(data, var) {
UseMethod("fun_run")
}
fun_run.default <- function(data, var) {
var <- rlang::enquo(var)
data_pull <- data %>% dplyr::pull(!(!var))
# find the lengths of the number of missings in a row
tibble::as_tibble(c(rle(is.na(data_pull))))
}
fun_run.grouped_df <- function(data, var) {
var <- rlang::enquo(var)
tidyr::nest(data) %>% dplyr::mutate(data = purrr::map2(.x = data, .y = !(!var),
.f = fun_run)) %>% tidyr::unnest()
}
library(dplyr)
#>
#> Attaching package: 'dplyr'
#> The following objects are masked from 'package:stats':
#>
#> filter, lag
#> The following objects are masked from 'package:base':
#>
#> intersect, setdiff, setequal, union
airquality %>% fun_run(Ozone)
#> # A tibble: 35 x 2
#> lengths values
#> <int> <lgl>
#> 4 FALSE
#> 1 TRUE
#> 4 FALSE
#> 1 TRUE
#> 14 FALSE
#> 3 TRUE
#> 4 FALSE
#> 6 TRUE
#> 1 FALSE
#> 1 TRUE
#> ... with 25 more rows
# doesn't work
airquality %>% group_by(Month) %>% fun_run(Ozone)
#> Error in mutate_impl(.data, dots) : Evaluation error: object 'Ozone' not found.
# does work
airquality %>% group_by(Month) %>% fun_run("Ozone")
#> # A tibble: 37 x 3
#> Month lengths values
#> <int> <int> <lgl>
#> 5 4 FALSE
#> 5 1 TRUE
#> 5 4 FALSE
#> 5 1 TRUE
#> 5 14 FALSE
#> 5 3 TRUE
#> 5 4 FALSE
#> 6 6 TRUE
#> 6 1 FALSE
#> 6 1 TRUE
#> # ... with 27 more rows