R Tip: Get Out of the Habit of Calling View() Directly

March 4, 2018

(This article was first published on R – Win-Vector Blog, and kindly contributed to R-bloggers)

R tip: get out of the habit of calling View() directly.

View() only works correctly in interactive environments, not currently in RMarkdown contexts. It is better to call something else that safely dispatches to View(), or to something else depending if you are in an interactive or non-interactive session.

The following code will work interactively, in RMarkdown, or even in a reprex.

#' Invoke a spreadsheet like viewer when appropriate.
#' @param x R object to view
#' @param title title for viewer
#' @param n number of rows to show
#' @return invoke view or format object
view <- function(
  title = as.character(substitute(x)), 
  n = 200) {
  UseMethod("view", x)
view.data.frame <- function(
  title = as.character(substitute(x)), 
  n = 200) {
  if(interactive()) {
    View(x, title = title)
  } else {
               character.only = TRUE, 
               quietly = TRUE)) {
      knitr::kable(head(x, n = n), 
                   caption = title)
    } else {
      print(format(head(x, n = n)))


The above code is a nice safe way to view frames which falls back to a low dependency solution when needed.

For more on wrapr::stop_if_dot_args() please see R Tip: Force Named Arguments.

To leave a comment for the author, please follow the link and comment on their blog: R – Win-Vector Blog.

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


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)