0

I have several dataframes that I have called and placed within a list as follows:

plots_list <- list(data_1, data_2, data_3, data_4, data_5)

I have defined a function, which takes in data from each dataframe and plots the residuals:

residual_plots <- function(data) {
  ggplot(data, aes(x = x, y = y)) +
    geom_point(
      aes(color = col1,
          shape = col2),
      na.rm = T,
      size = 1.2
    ) +
    geom_hline(
      yintercept = 0,
      colour = "dimgray",
      linetype = "solid",
      size = 0.25
    ) +
    geom_abline(
      intercept = 0,
      slope = 0.1,
      colour = "dimgray",
      linetype = "dashed",
      size = 0.25
    ) +
    geom_abline(
      intercept = 0,
      slope = -0.1,
      colour = "dimgray",
      linetype = "dashed",
      size = 0.25
    )                   
}

Since I have multiple dataframes, I wanted to use a for-loop to get the job done quickly. This is the code I have used:

res_plot_list <- vector("list", length = length(plots_list))
for (i in (plots_list)) {
  res_plot_list[[i]] <- residual_plots(i)
}
ml <- marrangeGrob(res_plot_list, nrow = 2, ncol = 3)
ml

I have tried multiple variations to try and get all the plots onto the same page but I keep hitting some form of dead end. As of now, when I use this code, I keep running into the following error:

Error in `[[<-`(`*tmp*`, i, value = residual_plots(i)) : 
  invalid subscript type 'list'

I would really appreciate any help on how I can best approach this problem, because I am unable to find the right one. Thanks!

1 Answer 1

1

i in the for loop is the dataset hence res_plot_list[[i]] fails. Try -

for (i in seq_along(plots_list)) {
  res_plot_list[[i]] <- residual_plots(plots_list[[i]])
}

Or why not just use lapply -

res_plot_list <- lapply(plots_list, residual_plots)
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you so much your time and answer! Using the lapply() function has helped me plot them all on the same page!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.