2013-01-01 33 views
0

也許,我沒有很好地定義這個問題。我似乎不明白R從sapply中退出。我有一個分層數據的大型數據框。大約一半的列是因素,一半是數字。我想獲得一個包含一些因素的新數據框,並對數字列進行求和,但我希望這些和數保持按因子水平分開。R中的分層數據如何在維護樹的同時求和子集?

例如,從下面的示例數據中,我想使狀態,分區,分支的數據框相同,但對相同類型但具有不同顏色的訂單的數據進行求和。我在考慮迭代使用sapply會這樣做,但我似乎無法讓它工作。

樣本數據:

state district branch order colour number cost amount 
CA central newtown shoes black 6 25.50 127.40 
CA central newtown shoes brown 3 32.12 75.40 
CA central newtown gloves blue 15 12.20 157.42 
CA central newtown gloves black 9 8.70 65.37 
CA central columbus shoes black 12 30.75 316.99 
CA central columbus shoes brown 1 40.98 45.00 
CA central columbus gloves blue 47 11.78 498.32 
CA central columbus gloves black 23 7.60 135.50 

回答

1

另一個工作爲aggregate。呼喚你的數據幀dat

aggregate(cbind(cost, amount) ~ state+district+branch+order, data=dat, FUN=sum) 

## state district branch order cost amount 
## 1 CA central columbus gloves 19.38 633.82 
## 2 CA central newtown gloves 20.90 222.79 
## 3 CA central columbus shoes 71.73 361.99 
## 4 CA central newtown shoes 57.62 202.80 

在〜左側,cbind用於指示,我們要分開每個列。如果指定了cost + amount,則這意味着這裏的總和,因爲它們是數字。在〜的右邊,我們有因素,所以+意味着我們按每個因子的每個等級彙總。

+0

嗯,這看起來很不錯......但我得到一個錯誤,當我用它寫成:'不能強制類「公式」到data.frame'中。該公式似乎是由於〜,但它在不同的包中使用不同。我沒有加載任何軟件包,只是簡單的香草R.我嘗試使用=列表(狀態,地區,分支,秩序),但這也不起作用。 – Suz