我有一个包含多个因素交互作为列名的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
似乎会在必要时引用 key
和 value
参数,那么有没有办法在 key
定义中评估 paste0(...)
?
eval(parse(text = paste0(...)))
方法? - LAP