[R] Save file as Fixed Width using sprintf()
arun
smartpink111 at yahoo.com
Fri Apr 11 22:10:48 CEST 2014
Hi,
May be this helps:
xx <- paste(aa, collapse=' ')
set.seed(14)
myMat <- matrix(rnorm(9), 3,3)
sprintf(xx,myMat[,1],myMat[,2],myMat[,3])
# [1] "-0.661850 1.497154 -0.064881"
# "1.718954 -0.036141 1.068994"
# [3] "2.121667 1.231945 -0.376965"
do.call(sprintf,c(xx,split(myMat,col(myMat))))
#[1] "-0.661850 1.497154 -0.064881"
#"1.718954 -0.036141 1.068994"
#[3] "2.121667 1.231945 -0.376965"
A.K.
On Friday, April 11, 2014 3:56 PM, "Doran, Harold" <HDoran at air.org> wrote:
I have working code to write a file out as fwf as shown below. I have one question to try and automate this I cannot get to work.
I am generating thousands of data files for a simulation to be run outside of R and each file varies in its dimensions. So I am trying to write code that can write the fwf based on the dimensions of each file generated as shown below. I have commented this code with an example to show where I am stuck.
### Create a sample data matrix
myMat <- matrix(rnorm(9), 3,3)
### Create the vector of format strings to be equal to the length of the columns in myMat
aa <- rep('%4f', ncol(myMat))
xx <- paste(aa, sep='', collapse='')
### Now I could just do this below and it works
(out <- sprintf(xx, myMat[, 1], myMat[, 2], myMat[, 3]) )
out <- as.matrix(out) # convert to a character matrix
dimnames(out) <- list(rep('', nrow(out)), '') # blank row and column names
noquote(out) ## sink this file to a directory
But, the fact that the dimensions of my matrix vary at each iteration means I need to automate this part in the sprint().
myMat[, 1], myMat[, 2], myMat[, 3])
I think that's needed because something like the following does not work
(out <- sprintf(xx, myMat[, 1:3]) )
So, I thought about trying smoething like this
cols <- paste(paste('myMat[, ', 1:ncol(myMat), sep=''), ']', sep='')
cols <- paste(cols, collapse=', ')
But, this is a string with quotation marks, so I thought using cat() might work, but it does not
(out <- sprintf(xx, cat(cols) ) )
Anyone have a suggestion for the right way to do this, this is getting messy.
Thank
Harold
[[alternative HTML version deleted]]
______________________________________________
R-help at r-project.org mailing list
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.
More information about the R-help
mailing list