[R] Exporting to file: passing source name to file name in loop

Fernando Henrique Ferraz P. da Rosa mentus at gmx.de
Sun Nov 14 17:20:35 CET 2004


Laura Quinn writes:
> Apologies - Sunday afternoon coding, not my forte.
> 
> I am trying to pass the name of my input variable "x" (my.data) into the
> name of my output file, and am wanting to combine this with a "count"
> value.
> 
> I hope that this code is a little more readable (though I seem to be
> having problems pasting the formatting into my email composition):
> 
> fun_pca_vector_movie_plot <- function (x,y,z,t) {
>   zz=seq(1,(nrow(x)-t),by=t);jj=seq(t+1,(nrow(x)),by=t)
>     for(i in seq(along=zz)){
>        plot.new()
> 	png(file=(paste(as.character(x),".",i,".png",sep="")),width=240,height=240)
>         pca<-prcomp(x[zz[i]:jj[i],], retx=T, center=T,scale=T)
>           {
>            par(mfrow=c(1,z))
>              for(i in 1:z){
>                 image(east,north,t(map.matrix),col=my.colors,axes=T,
>                       xlab="",ylab="")
>                 text(y[,3],y[,2],labels=as.character(y[,1]))
>                 title(paste("Component",i,"Step:"))
>               	arrows(y[,3],y[,2],(y[,3]+50*(pca$rotation[i,1:(ncol(x)/2)])),
>                       (y[,2]+50*(pca$rotation[i,((ncol(x)/2)+1):(ncol(x))])),
>                        angle=30,length=0.05,code=2)
>             }
>          box()
>          }
>        dev.off()
>      }
>    }
> 
> I get a "syntax error" relating to the as.character(x) part of the file
> name - if I remove this, the code works fine for the rest of the file
> extension. I have tried deparse(x) but this returns a file extension of
> the following nature:
> 
> structure(list(f1 = c(5.56358661715647, 6.10364037003176,
> 6.24040147126807, .10.png

        You should try something like:

        png(file=paste(substitute(x),".",i,".png",sep=""),width=240,height=240)

        Also, drop the 'plot.new()', it's useless. png() already sets up
a new ploting device.


--
Fernando Henrique Ferraz P. da Rosa
http://www.ime.usp.br/~feferraz




More information about the R-help mailing list