convert S4 DataFrame of Rle objects to sparse matrix in R

南楼画角 提交于 2020-01-02 06:56:08

问题


In the R language, I have an S4 DataFrame consisting of Rle encoded elements. The data can be simulated using following code

x = DataFrame(Rle(1:10),Rle(11:20),Rle(21:30))

Now, I want to convert this DataFrame to a sparse matrix from the Matrix package. On a usual data.frame, one can do

Matrix(x,sparse=TRUE)

However, this does not work for DataFrames, as it gives the following error:

Matrix(x,sparse=TRUE)

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

Any ideas on how to convert between data types in a rather efficient way?

Thanks!


回答1:


I'm posting Michael Lawrence's answer here to avoid the link breaking. Also it needed a small bug fix to handle the case when a Rle ends with zero:

# 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
})


来源:https://stackoverflow.com/questions/29609275/convert-s4-dataframe-of-rle-objects-to-sparse-matrix-in-r

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!