问题
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