简体   繁体   English

不能在dplyr中使用!! arg进行突变调用

[英]Can't use !!arg in dplyr for mutate call

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. 以下函数在创建时会引发错误,但是如果我删除mutate调用,它会很好地工作。

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

The naming of the column on the lhs of assignment goes along with the assignment operator ( := ) instead of the = operator. 分配的lhs上的列命名与分配运算符( := )一起使用,而不是=运算符。 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 ( !! ) 因此,我们可以将quosure('y'从enquo )转换为字符串( quo_name ),然后进行求值( !!

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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM