Recently, I made an algorithm to compute mean of certain events. It took some time to come up with this algorithm, so I thought it will be good to share.

Following is the code that is very similar to what I made for extracting the events, but less complex. I first generate 2 data frames, corresponding to events dataset (dat1) and elections dataset (dat2) respectively, as described above. I then match a date from dat2, to date in dat1 (for simplicity, date on both is not in correct format), in order to extract events from dat1.

Here is the R code to do that:

rm(list = ls())

# creating two different dataframes

date1<-c(2,4,6,8,10,12, 14, 16, 18,20)

events<-rnorm(10, 100, 50)

dat1<-as.data.frame(cbind(date1,events))

date2<-c(6, 12, 16)

dat2<-as.data.frame(date2)

dat1$sn1<-1:nrow(dat1)

dat2$sn2<-1:nrow(dat2)

# extracting sum of 3 rows

i<-1

for(i in dat2$sn2) {

c1<-dat2$date2[i]

n<-dat1$sn1[dat1$date1==c1]

av<-0

j<-0

while ((n<(n+2)) & n<nrow(dat1) ) {

av<-av+dat1$events[n]

n<-n+1

j<-j+1

}

dat2$av[i]<-av/j

}

names(dat2)[names(dat2)=="av"] <- "Average events"

print(dat2)

(In the output, dat2 will have additional column that contains average number of events)

**Problem**: I had to extract 1 year of events in an event data set from a given date. But the date from which the 1 year starts had to be brought from another dataset on elections. In other words, I had to match the election day from election data, and then compute mean of all daily events from the events dataset, covering a period of 1 year from the date.**Simulation**Following is the code that is very similar to what I made for extracting the events, but less complex. I first generate 2 data frames, corresponding to events dataset (dat1) and elections dataset (dat2) respectively, as described above. I then match a date from dat2, to date in dat1 (for simplicity, date on both is not in correct format), in order to extract events from dat1.

**Simulation Problem:**For simplicity, the following is a code to extract 3 events from that date (including that date); i.e. events until 2 rows after the date. I then have to average the three events. Note, if there are less than 3 events remaining, then I have to make an average of 2 ( or if there is only 1 remaining event, then just one).Here is the R code to do that:

rm(list = ls())

# creating two different dataframes

date1<-c(2,4,6,8,10,12, 14, 16, 18,20)

events<-rnorm(10, 100, 50)

dat1<-as.data.frame(cbind(date1,events))

date2<-c(6, 12, 16)

dat2<-as.data.frame(date2)

dat1$sn1<-1:nrow(dat1)

dat2$sn2<-1:nrow(dat2)

# extracting sum of 3 rows

i<-1

for(i in dat2$sn2) {

c1<-dat2$date2[i]

n<-dat1$sn1[dat1$date1==c1]

av<-0

j<-0

while ((n<(n+2)) & n<nrow(dat1) ) {

av<-av+dat1$events[n]

n<-n+1

j<-j+1

}

dat2$av[i]<-av/j

}

names(dat2)[names(dat2)=="av"] <- "Average events"

print(dat2)

(In the output, dat2 will have additional column that contains average number of events)