Reputation: 3
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)
Upvotes: 0
Views: 1397
Reputation: 19867
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=""))
}
}
Upvotes: 1