用dplyr quos引用...中的单个变量 [英] Referring to individual variables in ... with dplyr quos

查看:72
本文介绍了用dplyr quos引用...中的单个变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

阅读使用dplyr编程的指南,我可以参考全部一次 ... 变量。但是我该如何单独使用它们呢?

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

这里有一个计算两个变量的函数。它成功使用 quos() !!!

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

现在我要 tidyr :: spread 第二个变量,在本例中为 am 列。当我添加到函数中时:

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)

我得到:


错误:列指定无效

Error: Invalid column specification

如何我应该只引用 cols <-quos(...)列表的第二个变量吗?

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

推荐答案

目前尚不清楚价差是否可以与 quosure 一起使用。一种选择是对字符串使用 spread _

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

这篇关于用dplyr quos引用...中的单个变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆