【问题标题】:Converting data frame into matrix将数据框转换为矩阵
【发布时间】:2015-11-05 12:12:20
【问题描述】:

如何将我的数据框“水果”转换为矩阵

> fruits
      Month Apple   Mango   Banana
1      June  149579 36051   28124
2      July  198742 37228   30354
3    August  397145 36483   31140
4 September  329559 37101   31588
5   October  144107 35917   29444
6  November   19432  8587    5382
7  December       0     0       0

我想把月份和水果的名字作为矩阵的头

【问题讨论】:

  • 你能显示预期的输出吗?你需要library(reshape2);acast(melt(fruits, id.var='Month'), variable~Month, value.var='value')还是as.matrix('row.names<-'(fruits[-1], fruits[,1]))
  • 你是救世主。谢谢你。我正在寻找第二个答案。

标签: r matrix


【解决方案1】:

我们可以在没有第一列的情况下对“fruits”列进行子集化,将“fruits”的行名更改为第一列并转换为matrixas.matrix)。

as.matrix('row.names<-'(fruits[-1], fruits[,1]))

【讨论】:

    【解决方案2】:

    我想这就是你想要的,但最好按照@akrun 的建议显示预期的输出:

    # convert the number columns to a matrix
    Mfruits <- as.matrix( fruits[ , 2:4 ] )
    # get the months as column names
    row.names( Mfruits ) <- fruits[ , 1 ]
    > Mfruits
               Apple Mango Banana
    June      149579 36051  28124
    July      198742 37228  30354
    August    397145 36483  31140
    September 329559 37101  31588
    October   144107 35917  29444
    November   19432  8587   5382
    December       0     0      0
    
    # check whether you really have a matrix
    str( Mfruits )
    int [1:7, 1:3] 149579 198742 397145 329559 144107 19432 0 36051 37228 36483 ...
    - attr(*, "dimnames")=List of 2
     ..$ : chr [1:7] "June" "July" "August" "September" ...
     ..$ : chr [1:3] "Apple" "Mango" "Banana"
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-06-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-04-11
      • 2020-10-31
      • 2021-11-12
      相关资源
      最近更新 更多