[R] printing a data.frame that contains a list-column of S4 objects

boB Rudis bob at rudis.net
Tue Jan 12 19:51:50 CET 2016


I wonder if something like:

format.list <- function(x, ...) {
  rep(class(x[[1]]), length(x))
}

would be sufficient? (prbly needs more 'if's though)

On Tue, Jan 12, 2016 at 12:15 PM, Jenny Bryan <jenny at stat.ubc.ca> wrote:
> Is there a general problem with printing a data.frame when it has a
> list-column of S4 objects? Or am I just unlucky in my life choices?
>
> I ran across this with objects from the git2r package but maintainer
> Stefan Widgren points out this example below from Matrix as well. I note
> that the offending object can be printed if sent through
> dplyr::tbl_df(). I accept that that printing doesn't provide much info
> on S4 objects. I'd just like those vars to not prevent data.frame-style
> inpsection of the entire object.
>
> I asked this on stack overflow, where commenter provided the lead to the
> workaround below. Is that the best solution?
>
> library(Matrix)
>
> m <- new("dgCMatrix")
> isS4(m)
> #> [1] TRUE
> df <- data.frame(id = 1:2)
> df$matrices <- list(m, m)
> df
> #> Error in prettyNum(.Internal(format(x, trim, digits, nsmall, width, 3L, : first argument must be atomic
> #> Error in prettyNum(.Internal(format(x, trim, digits, nsmall, width, 3L, : first argument must be atomic
>
> ## fairly costly workaround
> df2 <- df
> df2[] <- lapply(df2, as.character)
> df2
> #>   id                         matrices
> #> 1  1 <S4 object of class "dgCMatrix">
> #> 2  2 <S4 object of class "dgCMatrix">
>
> ## dplyr handles original object better but not as well as workaround
> library(dplyr)
> ## use select to force dplyr to show the tricky column
> tbl_df(select(df, matrices))
> #> Source: local data frame [2 x 1]
> #>
> #>                                                                      matrices
> #>                                                                        (list)
> #> 1 <S4:dgCMatrix, CsparseMatrix, dsparseMatrix, generalMatrix, dCsparseMatrix,
> #> 2 <S4:dgCMatrix, CsparseMatrix, dsparseMatrix, generalMatrix, dCsparseMatrix,
>
> Thanks,
> Jenny
>
> Jennifer Bryan
> Associate Professor
> Department of Statistics and
>    the Michael Smith Laboratories
> University of British Columbia
> Vancouver, BC Canada
>
> ______________________________________________
> R-help at r-project.org mailing list -- To UNSUBSCRIBE and more, see
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.



More information about the R-help mailing list