簡體   English   中英

整理數據幀到R中的矩陣

[英]Tidy data frame to matrix in R

這是我的數據框的glimpse():

    $ 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,...

如何將其轉換為矩陣?

嘗試

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

這是一個處理行名的整潔替代函數(希望有幫助)

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()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM