2015-10-01 67 views
0

我正在运行R脚本来为多个监视井中的数据创建相关性分析。因此,我为一列的每口井创建了一个循环。在R studio中,我可以查看和导出图形。R:用于在另一个循环中保存绘图的循环

我想创建一个自动保存它们的解决方案。我希望你能帮助我。谢谢!

在最后一行,我写下了保存文件的命令,但我必须为它创建一个循环。任何想法如何使用数据来创建一个循环?

NH3 <- read.table("//laboratory data/Trendanalysis_R/NH3.csv",header=T,sep=",",dec=".") 
header<-read.table("//laboratory data/Trendanalysis_R/NH3.csv",header=F, sep=",", dec=".") 
header<-header[1,] 
Date<-NH3[,1] 
Date<-as.Date(Date,"%d/%m/%Y") 
library(Hmisc) 

for (i in 2:8){ 
    monitoring_well<-NH3[,i] 
    titel<-paste("Trend analysis of", header[,i]) 
    a=plot(Date,monitoring_well,ylab="Ammonia [mg/l]",main=titel,col.main="darkblue",pch=20,col="darkblue") 
    abline(lm(monitoring_well~Date),col="red") 
    corr_coeff<-rcorr(Date,monitoring_well,type="spearman") 
    df.corr_coeff.r=data.frame(corr_coeff$r) 
    df.corr_coeff.P=data.frame(corr_coeff$P) 
    corr_P_plot<-df.corr_coeff.P[1,2] 
    corr_r_plot<-df.corr_coeff.r[1,2] 
    corr_r_plot<-round(corr_r_plot^2*100,digits=1) 
    corr_r<-df.corr_coeff.r[1,2] 

    if(corr_r_plot == 100) {analysis<-"perfect correlation"} 
    if(corr_r_plot < 100) {analysis<-"very strong correlation"} 
    if(corr_r_plot <= 64) {analysis<-"strong correlation"} 
    if(corr_r_plot <= 36) {analysis<-"average correlation"} 
    if(corr_r_plot <= 16) {analysis<-"weak correlation"} 
    if(corr_r_plot <= 4) {analysis<-"very weak correlation"} 
    if(corr_r_plot == 0) {analysis<-"no correlation"} 

    if(corr_P_plot <= 0.05) {p_analysis<-"significant"} 
    if(corr_P_plot > 0.05) {p_analysis<-"insignificant"} 

    if(corr_r <0){direction<-"negative"} 
    if(corr_r >0){direction<-"positive"} 

    r<-round(corr_r,digits=2) 
    mtext(expression(r^2), line=0.5,adj=0) 
    mtext(paste(" = ",corr_r_plot,"% , ", "r = ",r,", ",direction, analysis,", ",p_analysis), side=3, line=0.5, adj=0) 

    #dev.print(png,file="//laboratory data/Trendanalysis_R/test01.png",width=861,height=553,units="px",pointsize=8) 
} 
+1

欢迎来到SO!请创建一个[最小示例](http://stackoverflow.com/help/mcve) – Cath

回答

0

你必须把你的png循环中,并使用paste0创建的文件名。我重新编写了代码以使其具有可重现性。

df <-matrix(runif(80),ncol=8) 
colnames(df) <-letters[1:8] 
for (i in 2:8){ 
titel<-paste("Trend analysis of", colnames(df)[i]) 
png(filename = paste0("c:/temp/test",i,".png"),width=861,height=553,units="px",pointsize=8) 
plot(df[,i],ylab="Ammonia [mg/l]",main=titel,col.main="darkblue",pch=20,col="darkblue") 
dev.off() 
} 
0

非常感谢您的帮助!我已经集成了命令到我的循环,如:

df<-matrix(runif(80),ncol=8) 
colnames(df)<-letters[2:8] 

for (i in 2:8){ 
    monitoring_well<-NH3[,i] 
    titel<-paste("Trend analysis of", colnames(df)[,i]) 
    png(filename = paste0("//Fileserver/ocm-data/13/039_Cork CC/07_ Derryconnell/laboratory data/Trendanalysis_R/test",i,".png"),width=861,height=553,units="px",pointsize=8) 
    plot(Date,df[,i],ylab="Ammonia [mg/l]",main=titel,col.main="darkblue",pch=20,col="darkblue") 
} 

但不幸的是,该错误“错误xy.coords(X,Y,xlabel,ylabel,登录): 'X' 和 'Y' 的长度不同“发生。我尝试了不同的选择,但我不知道,问题出在哪里。