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

From: Jim Lemon <bitwrit_at_ozemail.com.au>
Date: Fri 10 Feb 2006 - 11:29:57 EST

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@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 Received on Fri Feb 10 10:17:13 2006

This archive was generated by hypermail 2.1.8 : Fri 03 Mar 2006 - 03:42:27 EST