2015-11-05 79 views
1

我怎樣才能將我的數據幀,「水果」到矩陣轉換數據幀到矩陣

> 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 

我想要個月和水果的名稱作爲基質的頭

+0

您可以顯示預期輸出。你需要'library(reshape2); acast(melt(fruits,id.var ='Month'),variable〜Month,value.var ='value')'或者它是'as.matrix('row.names < - '(水果[-1],水果[,1]))' – akrun

+1

你是救世主。謝謝。我正在尋找第二個答案。 – Akshit

回答

2

我們可以子集「 fruit'列沒有第一列,在第一列更改'fruits'的行名稱並轉換爲matrixas.matrix)。

as.matrix('row.names<-'(fruits[-1], fruits[,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" 
相關問題