Menu Home

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

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.

Categories: Coding Tutorials

Tagged as:

jmount

Data Scientist and trainer at Win Vector LLC. One of the authors of Practical Data Science with R.

1 reply

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: