I have a problem where I am hoping to calculate some monthly measures for different entities but the code I am currently using appears to be very slow. I am wondering if perhaps you may know of a better solution.
A simplified version of my dataset is below. The problem is that one of datasets contains some 6m individual daily observations and my current method appears to be very slow.
date event id return
2000-07-06 2 1 0.1
2000-07-07 1 1 0.2
2000-07-09 0 1 0.6
2000-07-10 0 1 0.4
2000-07-15 2 1 0.7
2000-07-16 1 1 0.3
2000-07-20 0 1 0.1
2000-07-21 1 1 0.2
2000-07-06 1 2 0.3
2000-07-07 2 2 0.4
2000-07-15 0 2 0.6
2000-07-16 0 2 0.8
2000-07-17 2 2 0.9
2000-07-18 1 2 0.1
To calculate these measures I am running code that looks like the following:
for (j in 1:length(list.of.ids)) {
for (i in 1:(number.of.months) {
temp <- subset(data, data$date < FirstDayMonth[i+1] & data$date >= FirstDayMonth[i] & data$id == list.of.ids[j])
total[i,j+1] <- sum(temp$return, na.rm = TRUE)
}
}
Note: total[,] is a matrix with a time column and one column for each id and the number of rows equals every month in the dataset. I am hoping to have a matrix that stores all my monthly measures for ids and months. This loop allows me to calculate the monthly sum of returns by id and then store it in that matrix.
Again, the code above allows me to subset on a month period (by restricting my observations to be between the first day of two consecutive months) and on ids. The problem is, for my larger datasets this is very slow.
Are there any improvements to the code that will allow me to get my desired output faster?