3

I am writing a functional test in R for a program in C++. The typical output file has some columns as "string" and the other columns as "double". Then, I would like to use diff to compare the expected output file returned by R with the observed output file returned by C++.

In pseudo-C++, I simply do this:

stringstream ssTxt;
ssTxt.precision (7);
ssTxt.setf (ios::scientific);
for(i=0; i<10; ++i){
  ssTxt << names[i] << " " << values[0][i] << " " << values[1][i] << " " << values[2][i] << endl;
  // write in file and clear ssTxt
}

Here is a typical output:

item1 2.8200000e-01 500 4.1846912e-04

In R, I do that:

results <- data.frame(name="item1", val1=0.282, val2=500, val3=0.00041846912873)
write.table(x=format(results, digits=8, nsmall=7, scientific=TRUE), file=...)

Here is the output corresponding to the same data:

item1 2.82e-01 500 4.1846912e-04

As you can see, it almost works, but R doesn't add trailing 0 after "2.82". I prefer to change the R code rather than the C++ code. So how can I do that?

1 Answer 1

6

Have you tried
sprintf or formatC?

To be specific I think

sprintf("%e", 2.82e-01) 

should do the trick but as mentioned above have a look at help(sprintf), which describes the various formatting capabilities of this function ...

1
  • I hoped an option like "trailingzeros" would have worked, but indeed sprintf does the trick! As a result, I also need to use gsub to replace "NA" by "nan" (after sprintf, missing values are characters, i.e. "NA", not NA, and thus we can't use the "na" option of write.table).
    – tflutre
    Commented Dec 16, 2012 at 0:36

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.