简体   繁体   English

将Rdata和图形保存在循环中

[英]save Rdata and graphs in loops

I need to save some graphs and Rdata in a loop-like behaviour. 我需要以类似循环的方式保存一些图形和Rdata。 I have made a short example of what I need done. 我已经简短说明了我需要做的事情。 My problem is in my code the graph just overwrites each other, so I guess I am having trouble with dynamically naming them. 我的问题是在我的代码中图形只是相互覆盖,所以我想我在动态命名它们时遇到了麻烦。

for (i in seq(from = 100, to = 2000, by = 100)){
  x <- rnorm(1:3000)
  x <- x[seq(from=1, to=length(x),i)]

  e=0
  d <- matrix(ncol = 1, nrow = 91)
  for (f in seq(from=1, to=10,by=0.1)) { 
    e=e+1
    d[e] <- sum(abs(x)^f)
  }

  x = data.frame(d);
  names(x)='V1';
  x$V2 = seq(from = 1, to = 10, by = 0.1);


pdf("C:/Users/x.pdf", height=6, width=6)

ggplot(x, aes(x=x$V2, y = x$V1)) + 
  geom_line(alpha=1)

dev.off()

save.image(file = "output.Rdata")

}

Thanks! 谢谢!

I think the problem is that you are writing to the same file name "x" every time, without incrementing the file name on subsequent iterations of the loop. 我认为问题在于您每次都在写入相同的文件名“ x”,而不会在循环的后续迭代中增加文件名。 For example: 例如:

for (i in 1:10) { pdf(file=paste(i, "x.pdf", sep="")) plot(rnorm(1:10)) dev.off() }

The above would name the files x1.pdf, x2.pdf, x3.pdf... x10.pdf. 上面的文件名为x1.pdf,x2.pdf,x3.pdf ... x10.pdf。 Without the "i", each iteration would write to x.pdf. 如果没有“ i”,则每次迭代都将写入x.pdf。

Alternatively, you could make a call to pdf at the start of the loop before the curly braces. 或者,您可以在循环开始之前在花括号之前调用pdf。 Then dev.off() after the final curly brace. 最后的花括号之后是dev.off()。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM