ThePlowKing
ThePlowKing

Reputation: 341

Performing Calculations on a Data Frame by Date

I have a data frame in R in the following format:

enter image description here

(The dates are in the wrong format but I can change them fairly easily).

Now, I was wondering how I can perform operations on the data frame between certain dates - for example, say I want to find the average price for the day 5/18/2012, and then I want to find the average price for 5/19/2012, and then similarly for 5/20/2012, how would I go about doing so? Thanks in advance.

EDIT: One idea I did have was to use the identical(x,y) function to compare two dates, however since it is a very large data frame (about 300,000 rows) I'd prefer a more efficient way :)

Upvotes: 0

Views: 51

Answers (2)

Mostafa90
Mostafa90

Reputation: 1706

You can try to group by date and do the average something like that :

library(dplyr); 
data %>% group_by(RecordDate) %>% summarise(av = mean(Price));

Upvotes: 4

Roman Luštrik
Roman Luštrik

Reputation: 70623

You can use aggregate.

x <- Sys.time()
y <- seq(from = x, to = x + 5 * 3600*24, by = "day")
xy <- data.frame(date = rep(y, each = 5),
                 value = rnorm(length(y)))

aggregate(value ~ date, data = xy, FUN = mean)

                 date     value
1 2017-01-28 10:07:29 0.2921081
2 2017-01-29 10:07:29 0.9039815
3 2017-01-30 10:07:29 0.5616696
4 2017-01-31 10:07:29 0.9297463
5 2017-02-01 10:07:29 0.5149972
6 2017-02-02 10:07:29 0.4353255

> aggregate(value ~ date, data = xy, FUN = length)
                 date value
1 2017-01-28 10:07:29     5
2 2017-01-29 10:07:29     5
3 2017-01-30 10:07:29     5
4 2017-01-31 10:07:29     5
5 2017-02-01 10:07:29     5
6 2017-02-02 10:07:29     5

Upvotes: 3

Related Questions