[英]Melt function (R/reshape) delivering an error
My data look like this: 我的数据如下所示:
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
What I want is, two geom_path charts (one chart for alpha, one for beta) which compare the test and the control. 我想要的是比较测试和控件的两个geom_path图表(一个图表用于alpha,一个图表用于beta)。 Here's an example from Excel for a similar test: 这是来自Excel的类似测试示例:
I assume I will need to melt the data in some way to get what I want. 我认为我将需要以某种方式融化数据以获得我想要的东西。 But, the command 但是,命令
rawMelt <- melt(df, id.vars = c(Year, Month))
gives the error Error: id variables not found in data: 2017, 2018, October, November, December, January, February, March
. 给出错误Error: id variables not found in data: 2017, 2018, October, November, December, January, February, March
。 How would you melt these data so that I can make the graph I want? 您将如何融合这些数据,以便创建所需的图形?
This is what I eventually went with, should anyone else have this problem: 如果有人遇到这个问题,这就是我最终要解决的问题:
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.