将Rle对象的S4 DataFrame转换为R中的稀疏矩阵

时间:2015-04-13 15:31:26

标签: r s4

在R语言中,我有一个由Rle编码元素组成的S4 DataFrame。 可以使用以下代码

模拟数据
x = DataFrame(Rle(1:10),Rle(11:20),Rle(21:30))

现在,我想将此DataFrame转换为Matrix包中的稀疏矩阵。在通常的data.frame上,可以做

Matrix(x,sparse=TRUE)

但是,这对DataFrames不起作用,因为它会出现以下错误:

Matrix(x,sparse=TRUE)

Error in as.vector(data) :  no method for coercing this S4 class to a vector

有关如何以相当有效的方式在数据类型之间进行转换的任何想法?

谢谢!

1 个答案:

答案 0 :(得分:0)

我在这里张贴Michael Lawrence的answer以避免链接中断。当Rle以零结束时,它还需要一个小错误修复来处理这个案例:

# Convert from Rle to one column matrix
#
setAs("Rle", "Matrix", function(from) {
    rv <- runValue(from)
    nz <- rv != 0
    i <- as.integer(ranges(from)[nz])
    x <- rep(rv[nz], runLength(from)[nz])
    sparseMatrix(i=i, p=c(0L, length(x)), x=x,
                 dims=c(length(from), 1))
})


# Convert from DataFrame of Rle to sparse Matrix
#
setAs("DataFrame", "Matrix", function(from) {
  mat = do.call(cbind, lapply(from, as, "Matrix"))
  colnames(mat) <- colnames(from)
  rownames(mat) <- rownames(from)
  mat
})