使用`dplyr :: case_when`创建一个包含plotmath表达式的新列

时间:2018-06-27 01:47:25

标签: r dplyr tidyverse tibble plotmath

我想创建一个包含绘图算子表达式的新列,稍后我打算在分析管道的其他地方使用它。

这是我尝试过的一个最小示例。例如,在这里我试图创建一个名为label的新列,该列将根据y列的值而具有不同的plotmath表达式。

这似乎不起作用:

# loading needed libraries
library(tidyverse)

# creating a dataframe
df <- data.frame(x = c(1:10), y = c(rep("a", 5), rep("b", 5))) %>%
  tibble::as_data_frame(x = .)

# adding a new column with plotmath expression
df %>%
  dplyr::mutate(.data = .,
                label = dplyr::case_when(
                  y == "a" ~ paste(list(
                  "'This is'", "~alpha==", 1
                ), sep = ""),
                y == "b" ~ paste(list(
                  "'This is'", "~beta==", 2
                ), sep = "")))
#> Error in mutate_impl(.data, dots): Evaluation error: `y == "a" ~ paste(list("'This is'", "~alpha==", 1), sep = "")`, `y == "b" ~ paste(list("'This is'", "~beta==", 2), sep = "")` must be length 10 or one, not 3.

reprex package(v0.2.0)于2018-06-26创建。

1 个答案:

答案 0 :(得分:1)

错误消息显示每种情况都返回长度3。这是因为当您使用paste() sep列表时,您将获得与列表长度相同的向量,因此

paste(list(
              "'This is'", "~alpha==", 1
            ), sep = "")

返回长度为3的向量,而不是所需的1或10。相反,如果使用collapse的{​​{1}}参数,则会得到长度为1的向量。在上下文中:

paste()
相关问题