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

时间:2016-01-11 21:49:19

标签: r dataframe dplyr s4

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

我使用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"

2 个答案:

答案 0 :(得分:3)

另一种选择(可能带来比预期更大的后果)是:

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

答案 1 :(得分: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">

归功于@rawr,他最初在评论中提出建议。

相关问题