Facet_grid: Error in Factor() Object not Found

Viewed 286

I want to ggplot with facet_grid on this my type of data that contains a column with a [list of vectors][1] just the same way as this data in this answer and this answer.

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))

I got this error message at this stage of my R code Error in factor(phi, levels = phi, labels = paste("phi ==", phi)) : object 'phi' not found.

I think if I am able to solve this error, I can then move ahead.

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()

How do I get rid of this error: Error in factor(phi, levels = phi, labels = paste("phi ==", phi)) : object 'phi' not found

I want the output to be like this image 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). like this.

1 Answers

If you are open to a complete tidyverse workflow, you could use:

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()

This produces

enter image description here

Related