R - capturing elements of R output into text files R - capturing elements of R output into text files r r

R - capturing elements of R output into text files


A simple way is to convert the output that you want to print to file, and convert it to a text string via capture.output. then you can simply cat the output to the file.

dat<-data.frame(a=rnorm(100),b=rnorm(100),c=rnorm(100))mod<-lm(a~b+c,data=dat)out<-capture.output(summary(mod))cat(out,file="out.txt",sep="\n",append=TRUE)out<-capture.output(vcov(mod))cat(out,file="out.txt",sep="\n",append=TRUE)

this creates a file out.txt containing

Call:lm(formula = a ~ b + c, data = dat)Residuals:     Min       1Q   Median       3Q      Max -2.67116 -0.81736 -0.07006  0.76551  2.91055 Coefficients:            Estimate Std. Error t value Pr(>|t|)(Intercept)  0.01196    0.11724   0.102    0.919b            0.11931    0.12601   0.947    0.346c           -0.09085    0.13267  -0.685    0.495Residual standard error: 1.171 on 97 degrees of freedomMultiple R-squared: 0.0183, Adjusted R-squared: -0.001944 F-statistic: 0.9039 on 2 and 97 DF,  p-value: 0.4084               (Intercept)             b             c(Intercept)  0.0137444761 -0.0006929722 -0.0005721338b           -0.0006929722  0.0158784141  0.0042188705c           -0.0005721338  0.0042188705  0.0176018744


There are many ways:

  • use sink()
  • open a file via file() and write results to it
  • place your code in a file and run it via R CMD BATCH file.R which creates output
  • explicitly write results data via write.table() or its variants like write.csv()

This is fairly elementary so you will probably benefit from reading the 'Introduction to R' manual, or one of the numerous books on R.

The simplest solution may be

R> X <- rnorm(100)R> summary(X)   Min. 1st Qu.  Median    Mean 3rd Qu.    Max.  -2.480  -0.618  -0.223  -0.064   0.609   2.440 R> write.table(matrix(summary(X)[c(1,3,6)], nrow=1), \               file="/tmp/foo.txt", col.names=FALSE, row.names=FALSE)R> system("cat /tmp/foo.txt")-2.48 -0.223 2.44R> 

where I force the subset of summary() to be a matrix of one row.


The important thing here is to learn that the summary function, as in:

summary(Variable1)

doesn't print the summary. It works out the summary and then returns it. The command line processor does the printing, just before popping up the next '>' prompt.

Lots of R functions work like that. Hence you can nearly always get return values by assignment. So if you do:

x = summary(Variable1)

then it won't get printed. But then type 'x' and it will. The command line prints the last thing evaluated.

Once you've got 'x', you can use the Import/Export methods to save for later.