FooBar
FooBar

Reputation: 16528

Stargazer: Save to file, don't show in console

When I want to save my regression results with

stargazer(regressions[[reg]], out=myFile, out.header=FALSE

stargazer keeps also displaying/printing the result into the console. As I'm iterating over dozens of results, this ruins my overview and the log. Is there any way to explicitly tell stargazer not only to save the output to the file, but also not to print it additionally?

I'm on stargazer_5.1.

Upvotes: 16

Views: 15314

Answers (5)

Tomas da Nobrega
Tomas da Nobrega

Reputation: 73

I like to do the following:

sink(path/to/output.tex)
stargazer(model1, ...)
sink()

The first sink(path/to/output.tex) tells R to write console output to the specified file, the second sink() returns R to default setting, exhibit output on console.

Upvotes: 1

Marian Melnyk
Marian Melnyk

Reputation: 1

First of all, set working directory. Then if you run the following code, it will save a text file with stargazer results to your working directory folder.

model_results <- stargazer(model1, type = "text") capture.output(model_results, file = "model1.txt")

Upvotes: 0

Agile Bean
Agile Bean

Reputation: 7191

the easiest way to approach the problem is:

  1. store the output of stargazer in an object without an output file nor capture.output()

output <- stargazer(..., type="text")

this stores the output as an nx1 matrix which doesn't look nice so you must convert it in the second step

  1. convert the output object into a nice format

2.a) with dplyr:

output %>% paste(., collapse = "\n") %>% cat("\n")

2.b) without dplyr:

cat(paste(output, collapse = "\n"), "\n")

2.c) as a function if you really prefer this:

print_stargazer <- function(object) {
   cat(paste(object, collapse = "\n"), "\n")
}

and then use it like this:

output <- stargazer(..., type="text")
print_stargazer(object)

Upvotes: 0

wesselnv
wesselnv

Reputation: 99

well given the answer of eipi10, the only part you need is

bla <- capture.output(stargazer(..., out=output.file))

specifying the output file in stargazer and capture the output in something random, which you simply remove or overwrite for the next table. No need to define a new function.

Upvotes: 9

eipi10
eipi10

Reputation: 93891

You can write a function that captures the output of stargazer and saves it to a file without any output to the console. For example, adapting code from this SO answer:

mod_stargazer <- function(output.file, ...) {
  output <- capture.output(stargazer(...))
  cat(paste(output, collapse = "\n"), "\n", file=output.file, append=TRUE)
}

Then, to run the function:

mod_stargazer(myfile, regressions[[reg]], header=FALSE)

append=TRUE results in all your tables being saved to the same file. Remove it if you want separate files for each table.

Upvotes: 11

Related Questions