我正在尝试构建一个函数,允许我对以特定前缀开头的列执行函数。我正在努力弄清楚如何让名称评估为正确的东西。
我查看了dplyr
它谈论编程的网站,但无法弄清楚如何使其正确评估。
我正在使用dplyr
@hadley 介绍的 on CRAN (v0.70)的最新版本tidyeval
代表
library(tidyverse)
tbl1 <- tibble(
urn = c(1 ,2 ,3 ),
a_width = c(10,20,30),
a_height = c(12,13,14),
b_width = c(25,50,75),
b_height = c(25,50,75)
)
my_mean <- function(x, group) {
width <- paste0(quo_name(group), "_width")
height <- paste0(quo_name(group), "_height")
summarise(x,
!!paste0(group, "_mean_width") := mean(!!width),
!!paste0(group, "_mean_height") := mean(!!height)
)
}
my_mean(tbl1, "a")
# # A tibble: 1 x 2
# a_mean_width a_mean_height
# <dbl> <dbl>
# 1 NA NA
# Warning messages:
# 1: In mean.default("a_width") :
# argument is not numeric or logical: returning NA
# 2: In mean.default("a_height") :
# argument is not numeric or logical: returning NA