我有以下函数来描述变量
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))
}
Run Code Online (Sandbox Code Playgroud)
我想用它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
Run Code Online (Sandbox Code Playgroud)
问题是当我尝试应用相同的descrptive使用函数时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
Run Code Online (Sandbox Code Playgroud)
如何使用少量修改来更改功能以获得所需的功能?
你需要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
Run Code Online (Sandbox Code Playgroud)
dplyr插图' 使用dplyr编程 '有使用enquo和的详细描述!!
回应Axeman的评论,我不是100%为什么 group_by和describe在这里不起作用.但是,使用debugonce它的原始形式的功能
debugonce(describe)
df %>% group_by(g) %>% describe(x1)
Run Code Online (Sandbox Code Playgroud)
人们可以看到它evalue没有分组,只是一个长度为100的数字向量.