Posted on Categories Coding, TutorialsTags , ,

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.

One thought on “R Tip: Get Out of the Habit of Calling View() Directly”

Comments are closed.