7

I can use !! to filter by a user-given variable but not to modify that same variable. The following function throws an error when created, but it works just fine if I delete the mutate call.

avg_dims <- function(x, y) {
  y <- enquo(y)
  x %>%
    filter(!!y != "TOTAL") %>%
    mutate(!!y = "MEAN") %>%
    group_by(var1, var2)
}
overdisperse
  • 416
  • 3
  • 13

1 Answers1

8

The naming of the column on the lhs of assignment goes along with the assignment operator (:=) instead of the = operator. Also, the names should be either string or symbol. So, we can convert the quosure ('y' from enquo) to string (quo_name) and then do the evaluation (!!)

avg_dims <- function(x, y) {
 y <- enquo(y)
 y1 <- rlang::quo_name(y)
 x %>%
    filter(!!y != "TOTAL") %>%
    mutate(!!y1 := "MEAN") %>%
    group_by(var1, var2)
  }

avg_dims(df1, varN)

data

set.seed(24)
df1 <- data.frame(var1 = rep(LETTERS[1:3], each = 4), 
      var2 = rep(letters[1:2], each = 6), 
      varN = sample(c("TOTAL", "hello", 'bc'), 12, replace = TRUE), 
     stringsAsFactors = FALSE)
akrun
  • 874,273
  • 37
  • 540
  • 662
  • 1
    This helped me, but honestly, I do not understand it. Any more clarity anyone can add? Thanks in advance. – Sam Jan 11 '21 at 03:58