(Automatically Show Output)

July 22, 2018
By

(This article was first published on woodpeckR, and kindly contributed to R-bloggers)

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.

screen-shot-2018-07-22-at-3-24-38-pm.png

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

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

screen-shot-2018-07-22-at-3-24-38-pm.png

…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 on topics such as: Data science, Big Data, R jobs, visualization (ggplot2, Boxplots, maps, animation), programming (RStudio, Sweave, LaTeX, SQL, Eclipse, git, hadoop, Web Scraping) statistics (regression, PCA, time series, trading) and more...



If you got this far, why not subscribe for updates from the site? Choose your flavor: e-mail, twitter, RSS, or facebook...

Comments are closed.

Search R-bloggers

Sponsors

Never miss an update!
Subscribe to R-bloggers to receive
e-mails with the latest R posts.
(You will not see this message again.)

Click here to close (This popup will not appear again)