Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Is there a general problem with printing a data.frame when it has a list-column of S4 objects? Or am I just unlucky?

I ran across this with objects from the git2r package but maintainer Stefan Widgren points out this example from Matrix as well. I note that the object can be printed if sent through dplyr::tbl_df(). I accept that the printing doesn't provide much info on S4 objects; all I ask is no error.

UPDATED with slightly higher ambition: can the data.frame-like quality be preserved?

library(Matrix)
library(dplyr)
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
tbl_df(df)
#> Source: local data frame [2 x 2]
#> 
#>      id
#>   (int)
#> 1     1
#> 2     2
#> Variables not shown: matrices (list).

## 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,

## rawr points out that this does not error ... but loses the df quality
print.default(df)
#> $id
#> [1] 1 2
#> 
#> $matrices
#> $matrices[[1]]
#> 0 x 0 sparse Matrix of class "dgCMatrix"
#> <0 x 0 matrix>
#> 
#> $matrices[[2]]
#> 0 x 0 sparse Matrix of class "dgCMatrix"
#> <0 x 0 matrix>
#> 
#> 
#> attr(,"class")
#> [1] "data.frame"
like image 481
jennybryan Avatar asked Jan 11 '16 21:01

jennybryan


1 Answers

Another option (with potentially greater consequences than desired) is:

library(Matrix)

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

m <- new("dgCMatrix")
df <- data.frame(id = 1:2)
df$matrices <- list(m, m)
df

##   id  matrices
## 1  1 dgCMatrix
## 2  2 dgCMatrix
like image 121
hrbrmstr Avatar answered Oct 23 '22 01:10

hrbrmstr