【问题标题】:Tidy data frame to matrix in R整理数据框到R中的矩阵
【发布时间】:2015-05-25 13:31:19
【问题描述】:

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

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

如何将其转换为矩阵?

【问题讨论】:

    标签: r matrix dplyr tidyr


    【解决方案1】:

    试试

    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
    

    【讨论】:

      【解决方案2】:

      这是一个处理行名的整洁替代函数(希望它有帮助)

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

      【讨论】:

        猜你喜欢
        • 2012-08-15
        • 2013-06-15
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-11-21
        • 2020-04-08
        • 1970-01-01
        • 2014-02-26
        相关资源
        最近更新 更多