打印包含S4对象列表列的数据框

10

当一个 data.frame 其中包含 S4 对象的列表列时,打印是否存在一般问题?还是说我只是不太幸运?

我在使用来自 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个回答

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

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,他最初在评论中提出了这个建议。


1
我不会称之为“变通方法”。这会强制将第二列中的项目转换为完全不同的类。数据框的列不应包含列表。我怀疑它们也不应包含S4构造函数。经典的易错努力涉及POSIXlt类向量。我知道它们不应包含语言对象,如函数或R表达式。我认为您应该放弃数据框作为目标,使用不同的容器类。 - IRTFM

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接