Site icon R-bloggers

(Automatically Show Output)

[This article was first published on woodpeckR, and kindly contributed to R-bloggers]. (You can report issue about the content on this page here)
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.

Problem

It’s annoying to have to type the name of an object I just created in order to print its output in a script.

Context

A certain lightsaber-wielding stats professor of mine liked to point out that R doesn’t go out of its way to be helpful. If you write a line of code that creates an object and then run that line of code, there’s no message to tell you that the object has been successfully created. R doesn’t say “Task complete! What’s next?” or otherwise give you any indication that anything has happened. To actually view the object you just created, you have to type its name or run some other command on it.

Once in a while, this lack of transparency can be frustrating. What if I want to save objects and also view them in real time as they are created? Say I’ve used the handy prop.table function to transform a frequency table into a proportion table. I’d like to be able to view prop, prop.1 and prop.2 without typing their names and adding extra lines of code.

Solution

The same lightsaber-wielding stats professor who wished R would be a little more communicative taught me a trick to do just this: encase a command in parentheses to automatically print its output when it runs. Hence,

(prop <- with(polygon, table(revetment, pool)) %>% 
         prop.table()
)

…returns the same thing as typing the line without the parentheses and then adding

prop

on a new line.

Also note that this is different (better) than running the command without the assignment arrow, like this:

with(polygon, table(revetment, pool)) %>%
     prop.table()

…because the above doesn’t save the table you created, it just shows it to you once.

Outcome

Create objects and view them at the same time, while saving some typing. This is also great for use in RMarkdowns, because it will print the output below the code chunk without your having to add another line of code.

To leave a comment for the author, please follow the link and comment on their blog: woodpeckR.

R-bloggers.com offers daily e-mail updates about R news and tutorials about learning R and many other topics. Click here if you're looking to post or find an R/data-science job.
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.