将参数传递给使用dplyr的函数

7

我有以下函数来描述一个变量

library(dplyr)
describe = function(.data, variable){
  args <- as.list(match.call())
  evalue = eval(args$variable, .data)
  summarise(.data,
            'n'= length(evalue),
            'mean' = mean(evalue),
            'sd' = sd(evalue))
}

我想使用dplyr描述这个变量。

set.seed(1)
df = data.frame(
  'g' = sample(1:3, 100, replace=T),
  'x1' = rnorm(100),
  'x2' = rnorm(100)
)
df %>% describe(x1)
#     n        mean        sd
# 1 100 -0.01757949 0.9400179

问题在于当我尝试使用函数group_by应用相同的描述时,描述函数没有在每个分组中应用。
df %>% group_by(g) %>% describe(x1)
# # A tibble: 3 x 4
#       g     n        mean        sd
#   <int> <int>       <dbl>     <dbl>
# 1     1   100 -0.01757949 0.9400179
# 2     2   100 -0.01757949 0.9400179
# 3     3   100 -0.01757949 0.9400179

如何通过少量修改更改函数以获取所需结果?

2个回答

7
你需要tidyeval:
describe = function(.data, variable){
  evalue = enquo(variable)
  summarise(.data,
            'n'= length(!!evalue),
            'mean' = mean(!!evalue),
            'sd' = sd(!!evalue))
}

df %>% group_by(g) %>% describe(x1)
# A tibble: 3 x 4
      g     n        mean        sd
  <int> <int>       <dbl>     <dbl>
1     1    27 -0.23852862 1.0597510
2     2    38  0.11327236 0.8470885
3     3    35  0.01079926 0.9351509

dplyr文档 'dplyr编程' 详细介绍了如何使用 enquo!!

编辑:

针对Axeman的评论,我不确定为什么在这里使用group_by和describe无法工作。 然而,使用debugonce调试原始函数。

debugonce(describe)

df %>% group_by(g) %>% describe(x1)

可以看到,evalue并没有分组,只是一个长度为100的数字向量。


2
{btsdaf} - Axeman
{btsdaf} - marc1s
1
{btsdaf} - Axeman

0

Base NSE 似乎也可以工作:

describe <- function(data, var){

  var_q <- substitute(var)
  data %>% 
    summarise(n = n(),
              mean = mean(eval(var_q)),
              sd = sd(eval(var_q)))
}


df %>% describe(x1) 

   n       mean       sd
1 100 -0.1266289 1.006795



df %>% group_by(g) %>% describe(x1)
# A tibble: 3 x 4
      g     n       mean       sd
  <int> <int>      <dbl>    <dbl>
1     1    33 -0.1379206 1.107412
2     2    29 -0.4869704 0.748735
3     3    38  0.1581745 1.020831

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接