打印包含S4对象列表列的data.frame

jen*_*yan 9 r dataframe s4 dplyr

打印一个data.frameS4对象的列表列时是否存在一般问题?或者我只是不走运?

我用git2r包中的对象来讨论这个问题,但维护者Stefan Widgren也指出了这个例子Matrix.我注意到,如果通过发送对象可以打印dplyr::tbl_df().我接受打印不提供S4对象的大量信息; 我要问的是没有错误.

更高的抱负更新:可以保持data.frame类似的质量吗?

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"
Run Code Online (Sandbox Code Playgroud)

jen*_*yan 0

这是一种解决方法,可以得到不错的打印结果,但代价是覆盖data.frame(或者可以出于打印目的制作副本):

library(Matrix)
m <- new("dgCMatrix")
df <- data.frame(id = 1:2)
df$matrices <- list(m, m)
df[] <- lapply(df, as.character)
df
#>   id                         matrices
#> 1  1 <S4 object of class "dgCMatrix">
#> 2  2 <S4 object of class "dgCMatrix">
Run Code Online (Sandbox Code Playgroud)

感谢@rawr,他最初在评论中提出了建议。