整理数据帧到R中的矩阵

时间:2015-05-25 13:31:20

标签: r matrix dplyr tidyr

这是我数据框的一瞥():

    $ Row     (int) 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 1, 1, 1, 1,...
    $ Col     (int) 1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4,...
    $ Value    (dbl) 62049.67, 62040.96, 62053.02, 62039.31, 61993.53, 62035.00,...

如何将其转换为矩阵?

2 个答案:

答案 0 :(得分:5)

尝试

library(Matrix)
m1 <- as.matrix(with(yourdata, sparseMatrix(Row, Col, x=Value)))

或使用base R

m2 <- matrix(, max(yourdata$Row), max(yourdata$Col))
m2[as.matrix(yourdata[1:2])] <- yourdata$Value
m2

答案 1 :(得分:0)

这里有一个整齐的替代函数,用于处理行名(希望有帮助)

to_matrix = function(tbl, rownames = NULL){

tbl %>%
{
    if(
        !tbl %>% 
        { if(!is.null(rownames)) (.) %>% dplyr::select(- contains(rownames)) else (.) } %>%
        dplyr::summarise_all(class) %>% 
        tidyr::gather(variable, class) %>%
        pull(class) %>% unique %>% identical("numeric")
    ) warning("to_matrix says: there are NON-numerical columns, the matrix will NOT be numerical")

    (.)

} %>%
as.data.frame() %>%
{ 
    if(!is.null(rownames)) 
        (.) %>% 
        magrittr::set_rownames(tbl %>% pull(!!rownames)) %>%
        dplyr::select(- !!rownames)
    else (.) 
} %>%
as.matrix()
}

示例

cars %>% as_tibble() %>% to_matrix()