2017-08-02 29 views
0

我創建了一個函數來計算「運行」的數量或丟失或完整的數據 - 我希望這個和dplyr::group_by一起工作,所以我把它寫成S3方法 - 下面是一個此代碼的簡化示例。用tidyeval在map2裏面不加引號

不幸的是,我發現裸引號變量名稱不起作用,但引用它,這確實有效,奇怪的是。

下面是一個輸出的例子

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 

回答

2

其實你不希望使用map2,因爲你的第二個輸入(var)不與第一輸入變化的速度(在分組/嵌套data) 。此外,「臭氧」列隱藏在該點的嵌套數據中。您可以通過嘗試沒有任何tidyeval語法來執行代碼中看到這一點:

data <- airquality %>% group_by(Month) 
tidyr::nest(data) %>% dplyr::mutate(data = purrr::map2(.x = data, .y = Ozone, 
                 .f = fun_run)) %>% tidyr::unnest() 
#>Error in mutate_impl(.data, dots) : 
#> Evaluation error: object 'Ozone' not found. 

相反,你要使用標準map

tidyr::nest(data) %>% dplyr::mutate(data = purrr::map(.x = data, var = Ozone, 
                 .f = fun_run)) %>% tidyr::unnest() 

一旦重寫用於您的功能:

fun_run.grouped_df <- function(data, var) { 

    var <- rlang::enquo(var) 

    tidyr::nest(data) %>% dplyr::mutate(data = purrr::map(.x = data, var = !!var, 
                 .f = fun_run)) %>% tidyr::unnest() 

} 

這產生了你最後引用的例子的結果。

+0

啊!這產生了我想要的。 完美,非常感謝!我太深入思考嵌套的數據框,我過於複雜的東西。 –