如何使用字符串拼接来定义gather函数的关键参数

7

我有一个包含多个因素交互作为列名的tibble(请见下面两个因素的示例)。

ex <- structure(list(`Monday*FALSE` = 42.74, `Monday*TRUE` = 70.68, 
`Tuesday*TRUE` = 44.05, `Tuesday*FALSE` = 51.25, `Wednesday*TRUE` = 35.57, 
`Wednesday*FALSE` = 59.24, `Thursday*TRUE` = 85.3, `Thursday*FALSE` = 59.91, 
`Friday*TRUE` = 47.27, `Friday*FALSE` = 47.44, `Saturday*TRUE` = 62.28, 
`Saturday*FALSE` = 98.8, `Sunday*TRUE` = 57.11, `Sunday*FALSE` = 65.99), class = c("tbl_df", 
"tbl", "data.frame"), row.names = c(NA, -1L))

我想编写一个函数,可以汇总这个tibble,并基于因子的输入名称创建一个key名称。然而,以下代码不能按照预期工作,因为paste0返回一个字符串。

my_gather <- function(data, ...){
  vars <- enquos(...)
  data %>% 
    gather(key = paste0(!!!vars, sep = '*'), value = value, factor_key = TRUE)
}

my_gather(ex, day, cond) %>% head()
# A tibble: 6 x 2
  `paste0(day, cond, sep = ".")` value
  <fct>                          <dbl>
1 Monday*FALSE                    42.7
2 Monday*TRUE                     70.7
3 Tuesday*TRUE                    44.0
4 Tuesday*FALSE                   51.2
5 Wednesday*TRUE                  35.6
6 Wednesday*FALSE                 59.2

我试图用.替换*以使合法的语法名称,然后使用!!paste0捕获到sym中:

my_gather <- function(data, ...){
   vars <- enquos(...)
   data %>% 
     gather(key = !!sym(paste0(!!!vars, sep = '.')), value = value, factor_key = TRUE)
}

但它会导致错误:

!vars 中的错误:参数类型无效

gather 似乎会在必要时引用 keyvalue 参数,那么有没有办法在 key 定义中评估 paste0(...)


你能否采用臭名昭著的 eval(parse(text = paste0(...))) 方法? - LAP
好像也不起作用。 - Kuba_
1个回答

9

这个不可行,因为你对引号进行了双重解除:

!!sym(paste0(!!!vars, sep = '.'))

!!中的所有内容都会被正常评估,因此如果您使用另一个非引用运算符,则需要由另一个准引用函数处理。 paste0()不支持!!!

一般来说,最好使用像!!这样的复杂语法分几个步骤完成。这样更易读,也更少出错的机会。

第二件事是您正在使用enquos()对输入进行引用。这意味着它们可以是任何复杂表达式,而不仅仅是列名。如果您期望裸列,请改用ensyms(...)(或者如果您喜欢不带引号的字符串,则只需使用syms(c(...)))。

my_gather <- function(data, ...){
  # ensyms() guarantees there can't be complex expressions in `...`
  vars <- ensyms(...)

  # Let's convert all symbols to strings and return a character vector
  keys <- purrr::map_chr(vars, as.character)

  # Now we can use paste() the normal way. It doesn't support `!!!`
  # but the standard way of dealing with vector inputs is the
  # `collapse` argument:
  key <- paste0(keys, collapse = '*')

  # Equivalently, but weird:
  key <- eval(expr(paste(!!!keys, sep = "*")))

  # Now the key can be unquoted:
  data %>%
    gather(key = !!key, value = value, factor_key = TRUE)
}

是的,非常有见地。谢谢! - Kuba_

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接