[R] writing a file using both cat() and paste()

Adaikalavan Ramasamy ramasamy at cancer.org.uk
Thu Feb 9 13:45:16 CET 2006


With regards to the saving bit, you might want to try dput() or save()
as well.

On Thu, 2006-02-09 at 19:29 -0500, Jim Lemon wrote:
> Taka Matzmoto wrote:
> > Hi R users
> > 
> > I like to create a ASCII type file using cat() and paste()
> > 
> > x <- round(runif(30),3)
> > cat("vector =( ", paste(x,sep=""), " )\n", file = "vector.dat",sep=",")
> > 
> > when I open vector.dat it was a long ugly file
> > 
> > vector =( 
> > ,0.463,0.515,0.202,0.232,0.852,0.367,0.432,0.74,0.413,0.022,0.302,0.114,0.583,0.002,0.919,0.066,0.829,0.405,0.363,0.665,0.109,0.38,0.187,0.322,0.582,0.011,0.586,0.112,0.873,0.671, 
> > )
> > 
> > Also there was some problems right after opening parenthesis and before the 
> > closing parenthesis. Two comma were there
> > 
> > I like to to have a nice formatted one like below. That is, 5 random values 
> > per a line
> > 
> > vector =( 0.463,0.515,0.202,0.232,0.852,
> > 0.367,0.432,0.74,0.413,0.022,
> > 0.302,0.114,0.583,0.002,0.919,
> > 0.066,0.829,0.405,0.363,0.665,
> > 0.109,0.38,0.187,0.322,0.582,
> > 0.011,0.586,0.112,0.873,0.671)
> > 
> First, you might want to avoid using "vector", as that is the name of an 
> R function. Say you have a 30 element data vector as above. If you 
> wanted to write a fairly general function to do this, here is a start:
> 
> vector2file<-function(x,file="",values.per.line=5) {
>   if(nchar(file)) sink(file)
>   cat(deparse(substitute(x)),"<-c(\n")
>   xlen<-length(x)
>   for(i in 1:xlen) {
>    cat(x[i])
>    if(i<xlen) cat(",")
>    if(i%%values.per.line == 0) cat("\n")
>   }
>   cat(")")
>   if(i%%values.per.line) cat("\n")
>   if(nchar(file))sink()
> }
> 
> Jim
> 
> ______________________________________________
> R-help at stat.math.ethz.ch mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide! http://www.R-project.org/posting-guide.html
>




More information about the R-help mailing list