Press "Enter" to skip to content

Helpful R code for presenting output

I often use R to do analyses, and I've found that presentation of output can be... less than ideal. When I was in a hurry, I would do something like this:

> print("test.var=")
[1] "test.var="
> print(round(test.var,3))
[1] 11.797 11.247 12.582  7.575  9.427

This isn't pretty, but it is quick. Not satisfied with quick and dirty, I wrote this function:

pprint <- function(..., sep="", innersep=" ", outersep1="'", outersep2="'"){
	toPrint <- c();
	for (ii in 1:length(list(...))){
		# print a normal object like text (e.g. "testing ")
		if (length(list(...)[[ii]]) == 1){
			toPrint <- paste(toPrint, list(...)[[ii]], sep=sep);
		# printing a vector (e.g. x <- c(1:10))
		else if (length(list(...)[[ii]]) > 1) {
			tempString <- paste(outersep1, list(...)[[ii]][1], sep="");
			for (jj in 2:length(list(...)[[ii]]))
				tempString <- paste(tempString, list(...)[[ii]][jj], sep=innersep);
			tempString <- paste(tempString, outersep2, sep="");
			toPrint <- paste(toPrint, tempString, sep="");

pprint is basically a function which combines print and paste but with some options that allow for easier presentation. For example:

> pprint("test.var=",round(test.var,3))
[1] "test.var='11.797 11.247 12.582 7.575 9.427'"
> pprint("test.var=",round(test.var,3),innersep=", ")
[1] "test.var='11.797, 11.247, 12.582, 7.575, 9.427'"

I use this usually when I'm formatting output to turn in for a homework assignment. If you have any questions/comments/improvements, let me know.

One Comment

Leave a Reply

Your email address will not be published. Required fields are marked *