Dan
Dan

Reputation: 524

Finding the sum of unique dates

I am very new to R, and am working with a data set of payment details from a website I run. I have a data frame which includes the following columns:

¦  Date ¦ Amount ¦ Type

Each row is an individual payment with differing amounts. I would like to find a way, without looping through the 25,000 or so payments, to find the total payment amount on each day in the data set.

I have tried sum(sub$Amount[sub$Date == unique(sub$Date)]) but that throws the following error:

Warning message:
In sub$Date == unique(sub$Date) :
  longer object length is not a multiple of shorter object length

As I said, I'm very new to R, so I'm sure I'm missing something basic, but can't work out how to do this without a loop.

Upvotes: 1

Views: 350

Answers (4)

David Arenburg
David Arenburg

Reputation: 92292

Or

library(data.table)
setDT(sub)[, sum(Amount), by = Date]

Upvotes: 1

rnso
rnso

Reputation: 24545

Try using base R:

with(sub, tapply(Amount, Date, sum))

Upvotes: 3

juba
juba

Reputation: 49033

Very similar dplyr solution :

library(dplyr)
sub %>%
  group_by(Date) %>%
  summarize(sum=sum(Amount))

Upvotes: 0

martin
martin

Reputation: 3239

You can use ddply from the plyr library:

require(plyr)
ddply(sum, .(Date), summarize, sum=sum(Amount))

Upvotes: 1

Related Questions