【问题标题】:Melt function (R/reshape) delivering an error熔化函数(R/reshape)提供错误
【发布时间】:2018-10-05 18:39:09
【问题描述】:

我的数据如下所示:

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。您将如何融合这些数据,以便我可以制作我想要的图表?

【问题讨论】:

  • 改用c("Year","Month")。如果您想使用裸列名称,请尝试切换到tidyr::gather
  • 谢谢。我更喜欢melt 只是因为我在学习 tidyverse 之前就学会了使用它,但是我在很多其他事情上都使用 tidyr,我经常忘记简单的细节。

标签: r reshape2


【解决方案1】:

这是我最终选择的,如果其他人有这个问题:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-12-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-07-11
    • 1970-01-01
    相关资源
    最近更新 更多