Brian Carter Brian Carter - 2 months ago 16
R Question

I need to document R code/console similar to a SAS log

I work for a research department that is tired of paying half a million a year to SAS. As the only R/SAS dual user in the department, I have been tasked with leading the transition. Most of our analysts have been good sports about it, going more smoothly than I'd thought.

But we need a way to log our programs for documentation purposes, similar to what we did with SAS. The logs need to have simple metrics in them, number of observations when merging data, warnings/errors, probably all the output as well.

Some of this stuff is output in the console and I can sink() to save the thing, but there is a lot that isn't output. We can add extra code to programs to document these things -- nrows() before/after merging, for example --, but I want to make it easier for my analysts.

Can anyone point me in a direction to more easily output a more detailed log from R? A package or some function I've never heard of?

Thanks.

Answer

You might want to consider converting scripts into rmarkdown files. Compiling the rmarkdown files can yield log files which are much more potent than plain text files.

glimpse() for the dplyr() package is useful to get a quick view on the content of a dataframe. str() gives similar output for dataframes and works on other classes too.

library(dplyr)
glimpse(mtcars)

Observations: 32
Variables: 11
$ mpg  (dbl) 21.0, 21.0, 22.8, 21.4, 18.7, 18.1, 14.3, 24.4, 22.8, 19.2, 17.8, 16.4, 1...
$ cyl  (dbl) 6, 6, 4, 6, 8, 6, 8, 4, 4, 6, 6, 8, 8, 8, 8, 8, 8, 4, 4, 4, 4, 8, 8, 8, 8...
$ disp (dbl) 160.0, 160.0, 108.0, 258.0, 360.0, 225.0, 360.0, 146.7, 140.8, 167.6, 167...
$ hp   (dbl) 110, 110, 93, 110, 175, 105, 245, 62, 95, 123, 123, 180, 180, 180, 205, 2...
$ drat (dbl) 3.90, 3.90, 3.85, 3.08, 3.15, 2.76, 3.21, 3.69, 3.92, 3.92, 3.92, 3.07, 3...
$ wt   (dbl) 2.620, 2.875, 2.320, 3.215, 3.440, 3.460, 3.570, 3.190, 3.150, 3.440, 3.4...
$ qsec (dbl) 16.46, 17.02, 18.61, 19.44, 17.02, 20.22, 15.84, 20.00, 22.90, 18.30, 18....
$ vs   (dbl) 0, 0, 1, 1, 0, 1, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0...
$ am   (dbl) 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0...
$ gear (dbl) 4, 4, 4, 3, 3, 3, 3, 4, 4, 4, 4, 3, 3, 3, 3, 3, 3, 4, 4, 4, 3, 3, 3, 3, 3...
$ carb (dbl) 4, 4, 1, 1, 2, 1, 4, 2, 2, 4, 4, 3, 3, 3, 4, 4, 4, 1, 2, 1, 1, 2, 2, 4, 2...
Comments