【问题标题】:R - How to include symbols/equations in data frame variable names?R - 如何在数据框变量名称中包含符号/方程式?
【发布时间】:2018-09-04 16:41:30
【问题描述】:

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

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() 中,但无济于事。我如何实现这一目标?谢谢。

【问题讨论】:

  • 嗯,这是一个复杂的名字。但是,您不认为通过将其称为列名来从该列中提取值有点太难
  • 如果 unicode 值可用,您可以使用paste 创建表达式
  • df %&gt;% mutate(!! paste0("f(x) = ", "\u03B1", "/", "\u03C1") := c)我暂时没有符号码
  • 类似df %&gt;% mutate(!! paste0("f(x) = ", "\u03A3", "xi/i") := c)
  • 是的。我认为这对于我的大多数用例来说肯定已经足够好了。谢谢你的建议!标记为已解决。

标签: r parsing variables expression naming


【解决方案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

【讨论】:

  • 感谢@akrun 的快速回复!抱歉,我的原始问题不够清楚(我会编辑它),但我希望将实际的希腊字母符号作为变量名的一部分。使用!!as.character() 并没有为我做到这一点,即使在尝试将数据框导出为CSV 或.xlsx 之后也是如此。有没有办法做到这一点?
  • @hpy 看起来你需要 unicode 字符来评估
  • @hpy 可以查看here
  • 好的,我刚试过mutate(!!paste0("\u03B1") := c ),它成功了!一个实际的希腊字母现在是新变量的名称。谢谢!但是,我想知道是否有办法用expression() 做实际的数学方程?...
  • @hpy 你需要df %&gt;% mutate(!! paste0("\u03B1", "+", "\u03C1") := c)这样的东西吗
猜你喜欢
  • 1970-01-01
  • 2011-11-25
  • 1970-01-01
  • 2021-01-12
  • 1970-01-01
  • 1970-01-01
  • 2014-10-03
  • 2016-06-14
  • 1970-01-01
相关资源
最近更新 更多