Caroline
Caroline

Reputation: 470

Is there any way to change the way View works for different classes?

I have created an S3 class in R that is based on a list. However, I want it to display in View as as if it were a data frame. Basically, I want View to use the as.data.frame method to view it instead of showing it in the way it shows lists. Is there any way to do this?

Here's a trivial example:

as.myclass <- function(x) {
  x <- list(x = x, y = 1, z = 2)
  class(x) <- "myclass"
  return(x)
}

as.data.frame.myclass <- function(x) {
  return(x$x)
}

View(as.myclass(mtcars))                      # This is what it does
View(as.data.frame(as.myclass(mtcars)))       # This is what I would like the previous command to do

Upvotes: 0

Views: 283

Answers (1)

moodymudskipper
moodymudskipper

Reputation: 47320

If we define a method as.data.frame.myclass View() will work... unless you use Rstudio, which has its own version that takes precedence, and behaves differently.

If you use utils::View() you'll have the R gui output:

as.myclass <- function(x) {
  class(x) <- "myclass"
  return(x)
}

as.data.frame.myclass <- as.data.frame.list
utils::View(as.myclass(mtcars)) 

Now if you use Rstudio it'll be a bit more complex, we need to override it and make it generic :

View <- function(x, title) UseMethod("View")
View.default <- function(x, title) eval(substitute(
  get("View", envir = as.environment("package:utils"))(x,title)))
View.myclass <- function(x, title) eval(substitute(
  get("View", envir = as.environment("package:utils"))(as.data.frame(x),title)))
View(as.myclass(mtcars))   

It would be easier however if you can afford to keep the data.frame class along with myclass :

as.myclass <- function(x) {
  class(x) <- c("data.frame","myclass")
  return(x)
}
View(as.myclass(mtcars)) # without overriding `View()`!

Upvotes: 2

Related Questions