如何转换我的数据框,"水果"进入矩阵
php_curl
我希望将月份和水果命名为矩阵的头部
答案 0 :(得分:2)
我们可以在没有第一列的情况下对'fruits'列进行子集化,在第一列中更改'fruits'的行名称并转换为matrix
(as.matrix
)。
as.matrix('row.names<-'(fruits[-1], fruits[,1]))
答案 1 :(得分:1)
我想这就是你想要的,但是以@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"