Reputation: 349
How can I convert my data frame, "fruits" into a 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 19432 8587 5382
7 December 0 0 0
I want months and fruits name as the heads of the matrix
Upvotes: 2
Views: 176
Reputation: 7659
I guess this is what you want, but it would have been a good idea to show the expected output as @akrun suggests:
# 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"
Upvotes: 1
Reputation: 887741
We can subset the 'fruits' column without the first column, change the row names of 'fruits' by the first column and convert to matrix
(as.matrix
).
as.matrix('row.names<-'(fruits[-1], fruits[,1]))
Upvotes: 2