2014-04-22 109 views
1

我有數據以Excel爲:R-轉換成數據矩陣格式同其他基質

 Terms  Category Weight 

     email  TV   1.00 

     acccount Email  12.0 

     accept  Phone  3.00 

我還有其他的矩陣,其格式爲:

Terms TV Email Phone Contact Information Support ..... 

    achieve 1 0.  0  0   0    0 
    acquired 0 10.20 0  0   0    0 
    across 0 0  3.00 0   0   0 

現在我想轉換成以上數據轉換成以上格式像

Terms TV Email Phone Contact Information Support ..... 

    email 1 0.  0  0   0.0   0 
    acccount 0 12.0 0  0   0.0   0 
    accept 0 0  0  1.23  0   0 

我想通過程序R.任何幫助將不勝感激做到這一點。提前致謝。

+0

你能不能提供一些數據一個不錯的教程?這將是有益的閱讀[這個SO主題](http://stackoverflow.com/q/5963269/640783) –

+0

請檢查現在 –

+0

是的..但如何做到這一點? –

回答

3

您需要重新整理數據。安裝包「reshape2」如果你不已經擁有了它

下面的代碼來重塑你的數據

require(reshape2) 
df.reshape <-melt(df, id.var=c("Terms", "Category")) 
#where df is your data.frame to be reshaped 
#using both terms and category as ID variables 
#now reshape it to wide format by casting 
df.wide <-dcast(df.reshape, Terms~Category) 

注意這會給你NA對沒有在數據中存在對。 您可以用零,如果你想

輕易更換下面是使用reshape2 http://www.seananderson.ca/2013/10/19/reshape.html

+0

在'dcast'中刪除一個逗號 –

+0

感謝@DavidArenburg,現在修復 – infominer

+0

(+1)很好地使用'melt'和'dcast' –