R - 如何在数据框变量名中包含符号/方程?

问题描述 投票:1回答:1

假设我在R中有一个名为tibbledf数据框,如下所示:

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”)。

进一步编辑:这是一个复杂的例子。如果我想要这样的变量名怎么办:

complex math equation with big sigma and division

复杂示例的可能用例是使用facet绘制ggplot2::facet_wrap()标签或使用rmarkdown等将数据框渲染为表格时....

我试过在expression()paste()内嵌套str_c()无济于事。我该如何实现这一目标?谢谢。

r parsing variables expression naming
1个回答
1
投票

我们可以将它转换为符号或字符,然后在评估后执行:=!!

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
© www.soinside.com 2019 - 2024. All rights reserved.