2017-09-04 72 views
-2

我有一個交易數據集,從2013年1月1日至2016年11月1日有10個客戶。我手動爲每個客戶分割數據集,如下所示,但是我找不到如何創建一個循環來完成它。什麼是最好的循環?卡在R中創建循環

This is how my data set looks like for one customer

customer_1 <- transactions[1:47,] 
customer_2 <- transactions[48:94,] 
customer_3 <- transactions[95:141,] 
customer_4 <- transactions[142:188,] 
customer_5 <- transactions[189:235,] 
customer_6 <- transactions[236:282,] 
customer_7 <- transactions[283:329,] 
customer_8 <- transactions[330:376,] 
customer_9 <- transactions[377:423,] 
customer_10 <- transactions[424:468,] 
+1

許多用於按組操作數據幀的選項。 'dplyr'包中的'group_by()'函數是一個很好的開始。使用base R,可以使用'split()'函數或'tapply()'。或者data.table包有一個'by'參數。看到這個問題的想法https://stackoverflow.com/q/11562656/134830 –

+1

雖然它可以使用索引向量迭代地分割數據和'assign'動態創建變量,我認爲這是一個更好的想法將其分解成data.frames列表(https://stackoverflow.com/questions/17499013/how-do-i-make-a-list-of-data-frames/24376207#24376207)或(作爲@RichieCotton建議)保持一個框架和工作組。 – r2evans

+0

out < - split(transactions,f = transactions $ customer_id)會給你一個元素列表,每個元素將包含來自一個客戶的所有交易 –

回答

0

您應該使用拆分拆分數據幀:

out <- split(transactions, f = transactions$customer_id) 

然後,如果你想分配按客戶的變量,你可以做

counter = 1 
for (elt in out){ 
    assign(paste("customer", counter, sep ="_"), elt) 
    counter <- counter + 1 
} 

哪將創建變量customer_1,customer_2 ....

+2

這在技術上確實會做什麼要求,但我建議不要這樣做:與像這樣的數據,一般情況下,無論您對一個data.frame做什麼,您都會對其他人做的。當分解成不同的變量時,你必須手動編碼每一個變量,或者使用'ls()'和'get()'動態地進行編碼。它更直接(編碼,跟隨,調試)來處理data.frames列表。 – r2evans

+0

謝謝你們。 @ Emmanuel-Lin,我使用了你分享的代碼,它的工作原理,但客戶不合適。 Customer_1從第377行開始。我如何才能從第1行開始customer_1? –