[英]How do I loop a qqplot in ggplot2?
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. 我试图创建一个遍历数据集各列并保存每个变量的qq图的函数。 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.
我已经花了很多时间来寻找解决方案,但是我是R新手,因此无法成功地对我的数据应用任何答案。 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" 我给出的错误是,“ eval(expr,envir,enclos)中的错误:找不到对象'i'”
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)
The error happens because you are trying to pass a string as a variable name. 发生错误是因为您试图将字符串作为变量名传递。 Use
aes_string()
instead of aes()
使用
aes_string()
而不是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. nm[i]
适用于for(i in seq_along(names(x))
,但不适用于当前循环。您最好在函数中用i
替换所有nm[i]
,因为您想要的是变量名。
Finally, you use mybbs
instead of x
inside the function. 最后,在函数中使用
mybbs
而不是x
。 That means it will not work properly with any other data.frame. 这意味着它将无法与其他任何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=""))
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.