4

I am trying to build a function that will allow me to perform functions on columns that start with a specific prefix. I am struggling to figure out how to get the names to evaluate to the correct thing.

I've looked at the dplyr website where it talks about programming but couldn't quite figure out how to make it evaluate properly.

I am making use of the most current version of dplyr on CRAN (v0.70) where @hadley has introduced tidyeval

Reprex

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
Dan
  • 2,625
  • 5
  • 27
  • 42

1 Answers1

2

!!width returns the string "a_width". You have to do !!sym(width) to turn it into a name. Similarly for !!height.

Hong Ooi
  • 56,353
  • 13
  • 134
  • 187