[R] writing a file using both cat() and paste()
Jim Lemon
bitwrit at ozemail.com.au
Fri Feb 10 01:29:57 CET 2006
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
More information about the R-help
mailing list