假设我在R中有一个名为tibble
的df
数据框,如下所示:
df <- tibble(a = 1:3,
b = c("a", "b", "c"))
使用dplyr::rename()
重命名变量(或使用dplyr::mutate()
创建新变量)相当容易,包括使用:=
运算符取消引用,例如:
df <- df %>%
rename("the new b" := b) %>%
mutate(c = a + 1)
这给了我:
> df
# A tibble: 3 x 3
a `the new b` c
<int> <chr> <dbl>
1 1 a 2
2 2 b 3
3 3 c 4
但是,当我想用expression()
在变量名中包含数学符号或方程时,它不起作用,例如当我尝试使用希腊字母符号时,它会失败:
# Fails:
> df <- df %>%
+ mutate(expression(A~symbol:~alpha) = c)
Error: unexpected '=' in:
"df <- df %>%
mutate(expression(A~symbol:~alpha) ="
# Fails again:
> df <- df %>%
+ mutate(expression(A~symbol:~alpha) := c)
Error: The LHS of `:=` must be a string or a symbol
编辑/更新:要清楚,在上面的例子中我想得到实际的希腊字母符号(不是字母字符串“alpha”)。
进一步编辑:这是一个复杂的例子。如果我想要这样的变量名怎么办:
复杂示例的可能用例是使用facet
绘制ggplot2::facet_wrap()
标签或使用rmarkdown
等将数据框渲染为表格时....
我试过在expression()
或paste()
内嵌套str_c()
无济于事。我该如何实现这一目标?谢谢。
我们可以将它转换为符号或字符,然后在评估后执行:=
(!!
)
df %>%
mutate(!! as.character(expr) := c)
# A tibble: 3 x 4
# a `the new b` c `A ~ symbol:~alpha`
# <int> <chr> <dbl> <dbl>
#1 1 a 2 2
#2 2 b 3 3
#3 3 c 4 4
哪里
expr <- expression(A ~ symbol:~ alpha)
如果我们想要希腊字母(如@hpy评论),请使用unicode字符-for alpha它是\u03B1
df %>%
mutate(!! "\u03B1" := c)
# A tibble: 3 x 4
# a `the new b` c α
# <int> <chr> <dbl> <dbl>
#1 1 a 2 2
#2 2 b 3 3
#3 3 c 4 4
以上内容也可以扩展为包含一些表达方式
df %>%
mutate(!! paste0("\u03B1", "+", "\u03C1") := c)
# A tibble: 3 x 4
# a `the new b` c `α+ρ`
# <int> <chr> <dbl> <dbl>
#1 1 a 2 2
#2 2 b 3 3
#3 3 c 4 4