Facet_grid: 找不到 Factor() 对象中的错误

Facet_grid: Error in Factor() Object not Found

我想 ggplotfacet_grid 在我的数据类型上,它包含一个带有 [list of vectors][1] 的列,就像这个 and 一样。

set.seed(1)
df <- data.frame(xx = 1:10, x1 = rnorm(10), x2 = rnorm(10), x3 = rnorm(10), x4 = rnorm(10), x5 = rnorm(10), x6 = rnorm(10), x7 = rnorm(10), x8 = rnorm(10), x9 = rnorm(10), x10 = rnorm(10), x11 = rnorm(10), x12 = rnorm(10))
reshapp <- reshape2::melt(df, id = "xx")
new_df <- data.frame(y = reshapp$value, x = reshapp$xx, sd = rep(rep(c(sd = 1, sd = 3, sd = 5, sd = 10), each = 10), each = 3), phi = rep(rep(list(c(0.4, 0.4), c(0.45, 0.45), c(0.35, 0.6)), each = 10), 4))

new_df$sd <- factor(new_df$sd, levels = new_df$sd, labels = paste("sd ==", new_df$sd))

我在 R 代码 Error in factor(phi, levels = phi, labels = paste("phi ==", phi)) : object 'phi' not found.

的这个阶段收到此错误消息

我想如果我能解决这个错误,我就可以继续前进了。

new_df$phi <- with(new_df, factor(phi, levels = phi, labels = paste("phi ==", phi)))

ggplot(new_df, aes(x = reshapp$xx, y = reshapp$value)) +  geom_line() +  geom_point() + scale_y_continuous(expand = c(0.0, 0.00)) + labs(x = 'Time', y = 'Series') + facet_grid(sd ~ phi, scales = "free_y",  labeller = label_parsed) +  theme_bw()

如何消除此错误:Error in factor(phi, levels = phi, labels = paste("phi ==", phi)) : object 'phi' not found

我希望输出类似于 only that the 0.8 will be (0.4, 0.4), 0.9 will be (0.45, 0.45) and 0,95 will be (0.35, 0.6).

如果您对完整的 tidyverse 工作流程持开放态度,您可以使用:

library(dplyr)
library(tidyr)
library(ggplot2)

df %>% 
  pivot_longer(-xx) %>% 
  mutate(id = as.numeric(gsub("x", "", name))) %>% 
  arrange(id, xx) %>% 
  select(-id) %>% 
  mutate(sd = rep(rep(c(sd = 1, sd = 3, sd = 5, sd = 10), each = 10), each = 3),
         phi = rep(rep(list(c(0.4, 0.4), c(0.45, 0.45), c(0.35, 0.6)), each = 10), 4)) %>% 
  mutate(sd = factor(sd, levels = sd, labels = paste("sd =", sd)),
         phi = factor(phi, levels = phi, labels = gsub("c", "", paste("\U03D5 =", phi)))) %>%   
  ggplot(aes(x = xx, y = value)) +
  geom_line() + 
  geom_point() +
  scale_y_continuous(expand = c(0.0, 0.00)) +
  labs(x = "Time", y = "Series") +
  facet_grid(sd ~ phi, scales = "free_y") + 
  theme_bw()

这会产生