0

I am trying to create a function that loops through the columns of my dataset and saves a qq-plot of each of my variables. I have spent a lot of time looking for a solution, but I am an R novice and haven't been able to successfully apply any answers to my data. Can anyone see what I am doing wrong?

There error I am give is this, "Error in eval(expr, envir, enclos) : object 'i' not found"

library(ggplot2)
QQPlot <- function(x, na.rm = TRUE, ...) {
    nm <- names(x)
    for (i in names(mybbs)) {
            plots <-ggplot(mybbs, aes(sample = nm[i])) + 
                    stat_qq()
            ggsave(plots, filename = paste(nm[i], ".png", sep=""))
    }
}

QQPlot(mybbs)

1 Answer 1

1

The error happens because you are trying to pass a string as a variable name. Use aes_string() instead of aes()

Moreover, you are looping over names, not indexes; nm[i] would work for something like for(i in seq_along(names(x)), but not with your current loop. You would be better off replacing all nm[i] by i in the function, since what you want is the variable name.

Finally, you use mybbs instead of x inside the function. That means it will not work properly with any other data.frame.

Here is a solution to those three problems:

QQPlot <- function(x, na.rm = TRUE, ...) {
  for (i in names(x)) {
    plots <-ggplot(x, aes_string(sample = i)) + 
      stat_qq()
    #print(plots)
    ggsave(plots, filename = paste(i, ".png", sep=""))
  }
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you for helping me understand my errors and for the code to fix them! It worked like a charm!

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.