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

Jenny Bryan jenny at stat.ubc.ca
Tue Jan 12 18:15:14 CET 2016


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



More information about the R-help mailing list