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

[This article was first published on R – Win-Vector Blog, 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.

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(
  x, 
  ...,
  title = as.character(substitute(x)), 
  n = 200) {
  UseMethod("view", x)
}
view.data.frame <- function(
  x, 
  ...,
  title = as.character(substitute(x)), 
  n = 200) {
  wrapr::stop_if_dot_args(substitute(list(...)), 
                          "view")
  if(interactive()) {
    View(x, title = title)
  } else {
    if(require("knitr", 
               character.only = TRUE, 
               quietly = TRUE)) {
      knitr::kable(head(x, n = n), 
                   caption = title)
    } else {
      print(format(head(x, n = n)))
    }
  }
}

view(mtcars)

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 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.

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)