熔化函数 (R/reshape) 传递错误

Melt function (R/reshape) delivering an error

我的数据是这样的:

set.seed(123)
library(tidyverse)
library(reshape2)
Year <- c(2017, 2017, 2017, 2018, 2018, 2018)
Month <- c(10, 11, 12, 1, 2, 3)
alpha_test <- runif(n = 6, min = 0.2, max = 0.25)
alpha_control <- runif(n = 6, min = 0.17, max = 0.22)
beta_test <- runif(n = 6, min = 0.01, max = 0.1)
beta_control <- runif(n = 6, min = 0.03, max = 0.05)

df <- tibble(Year, Month, alpha_test, alpha_control, beta_test, beta_control)
df

我想要的是比较测试和控制的两个 geom_path 图表(一个图表用于 alpha,一个用于 beta)。这是来自 Excel 的类似测试示例:

我假设我需要以某种方式融化数据以获得我想要的。但是,命令

rawMelt <- melt(df, id.vars = c(Year, Month))

给出错误 Error: id variables not found in data: 2017, 2018, October, November, December, January, February, March。你会如何融化这些数据,以便我可以制作我想要的图表?

这就是我最终采用的方法,如果其他人遇到此问题:

rawMelt <- melt(df, id.vars = c("Year", "Month")) %>%
  mutate(
    theSource = ifelse(grepl("test", variable), "test", "control"),
    metric = ifelse(grepl("alpha", variable), "alpha", "beta"),
    monthText = paste0(Year, "_", ifelse(Month < 10, "0", ""), Month)
  ) %>%
  select(-variable)

g_maker <- function(theMetric) {
  theChart <- rawMelt %>%
    filter(metric == theMetric)
  g <- ggplot(theChart, aes(x = as.factor(monthText), y = value, group = theSource)) +
    geom_path(aes(color = theSource)) +
    scale_color_manual(values = c("red", "black")) +
    theme_minimal() + 
    xlab(NULL) +
    theme(axis.text.x = element_text(angle = 75, hjust = 1))
  return(g)
}

alpha_graph <- g_maker("alpha")
beta_graph <- g_maker("beta")
alpha_graph
beta_graph