R-如何在数据框变量名称中包含符号/等式?

时间:2018-09-04 16:41:30

标签: r parsing variables expression naming

假设我在R中有一个名为tibble的{​​{1}}数据帧,如下所示:

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()

编辑/更新:为清楚起见,在上面的示例中,我想获取实际的希腊字母符号( not 字母字符“ alpha”的字符串)。

进一步编辑:这是一个复杂的示例。如果我想要类似这样的作为变量名

,该怎么办?

complex math equation with big sigma and division

复杂示例的可能用例是使用# 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 进行绘制时使用facet标签或使用ggplot2::facet_wrap()将数据框呈现为表格等。

我尝试将rmarkdown嵌套在expression()paste()内无济于事。我该如何实现?谢谢。

1 个答案:

答案 0 :(得分: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字符-对于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