2017-01-31 5 views
-2

指定されたデータセットには銀行口座間の振替が含まれます。すべての行には、bank_accountとtransfer_amountが含まれています。目的は、銀行口座ごとに合計transfer_amountを計算し、これを新しいデータフレームに入れることです。この新しいデータフレームは、ユニークなbank_accounts(各銀行口座が複数回表示される古いものと同じではありません)と、転送された金額の合計で構成する必要があります。要約されたデータを使ってRで新しいデータフレームを作成するには?

例:最低の表が結果はアカウント名を含む列がaccountと呼ばれ、データセットがdata呼ばれると仮定すると、転送を含む列

Example: the lowest table is what the result should look like

+3

ようこそStackOverflow。これらのヒントを見て、[最小、完全で検証可能な例](http://stackoverflow.com/help/mcve)の作成方法と[Rの素晴らしい例を作成する]( http://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example)。おそらく、[良い質問をする]のヒント(http://stackoverflow.com/help/how-to-ask)も読む価値があるかもしれません。 – lmo

答えて

0

どのように見えるかですtransferと呼ばれている:

u <- unique(data$account) # get all unique bank account numbers 
data.new <- data.frame(matrix(NA, nrow=length(u), ncol=2)) #create a new dataset to collect the results 
for (i in 1:length(u)) { #open a loop, for every unique back account 
    data.new[i, 1] <- u[i] #record the bank account number in the first column of the new dataframe 
    data.new[i, 2] <- sum(data[data$account == u[i], "transfer"]) #sum all transfers related to this account and assign to the new dataframe 
} #close the loop 
0

あなたはaggregateでこれを行うことができます。画像に示されている入力データとしてdfを入力してください。

df <-data.frame(account_number = c(1,2,3,2,3), amount = c(50,23,12,34,56)) 

aggregate(amount ~ account_number, df, sum) 

    account_number amount 
1    1  50 
2    2  57 
3    3  68 
関連する問題