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