Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/r/82.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
R 将数据帧转换为矩阵_R_Matrix - Fatal编程技术网

R 将数据帧转换为矩阵

R 将数据帧转换为矩阵,r,matrix,R,Matrix,如何将数据帧“水果”转换为矩阵 > 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 194

如何将数据帧“水果”转换为矩阵

> 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

我想将月份和水果名称作为矩阵的头部

我们可以在不使用第一列的情况下对“水果”列进行子集,在第一列更改“水果”的行名称,并转换为矩阵(
as.matrix


as.matrix('row.names我想这是您想要的,但是最好按照@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"
#将数字列转换为矩阵

Mfruits您可以显示预期的输出。您是否需要
库(重塑);acast(melt(fruits,id.var='Month'),variable~Month,value.var='value')
或者它是
作为.matrix('row.names')您是救世主。谢谢。我正在寻找第二个答案。
# 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"