Referring to individual variables in … with dplyr quos

三世轮回 提交于 2019-12-24 03:04:27

问题


Reading the guide to programming with dplyr, I am able to refer to all ... variables at once. But how can I use them individually?

Here's a function that counts two variables. It succeeds using quos() and !!!:

library(dplyr) # version 0.6 or higher
library(tidyr)

# counts two variables
my_fun <- function(dat, ...){

  cols <- quos(...)

  dat <- dat %>%
    count(!!!cols)

  dat

}

my_fun(mtcars, cyl, am)

#> # A tibble: 6 x 3
#>     cyl    am     n
#>   <dbl> <dbl> <int>
#> 1     4     0     3
#> 2     4     1     8
#> 3     6     0     4
#> 4     6     1     3
#> 5     8     0    12
#> 6     8     1     2

Now I want to tidyr::spread the second variable, in this case the am column. When I add to my function:

result <- dat %>%
    tidyr::spread(!!!cols[[2]], "n", fill = 0)

I get:

Error: Invalid column specification

How should I refer to just the 2nd variable of the cols <- quos(...) list?


回答1:


It is not clear whether spread works with quosure or not. An option is to use spread_ with strings

my_fun <- function(dat, ...){

  cols <- quos(...)

  dat %>%
    select(!!! cols) %>% 
    count(!!! cols) %>%
    spread_(quo_name(cols[[2]]), "n", fill = 0)

   }

my_fun(mtcars, cyl, am)
# A tibble: 3 x 3
#   cyl   `0`   `1`
#* <dbl> <dbl> <dbl>
#1     4     3     8
#2     6     4     3
#3     8    12     2



回答2:


Use named parameters instead. If you're relying on doing different things to different elements of the ... list it would only make sense to be explicit so it's easier to understand what each input is doing and make it easier for you to manipulate.



来源:https://stackoverflow.com/questions/44166247/referring-to-individual-variables-in-with-dplyr-quos

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!