I have the following data frame in R which presents the number of purchases per year over a period of four years, for 4 customers. The member_since
variable shows the year when the customer joined the company.
id<-c(1,2,3,4)
member_since<-c(2014,2016,2015,2014)
X2014<-c(2,0,0,3)
X2015<-c(3,0,4,2)
X2016<-c(3,2,3,4)
X2017<-c(2,3,6,0)
df<-data.frame(id,member_since,X2014,X2015,X2016,X2017)
id member_since X2014 X2015 X2016 X2017
1 2014 2 3 3 2
2 2016 0 0 2 3
3 2015 0 4 3 6
4 2014 3 2 4 0
Now I am trying to create a new variable mean_purchase
to calculate the average number of purchases per year for each customer, from the year s/he joined. This means for example for customer 2
the total number of purchases should be divided by 2, but for customer 4
the sum of purchases should be divided by 4.
id member_since X2014 X2015 X2016 X2017 mean_purchase
1 2014 2 3 3 2 2.5
2 2016 0 0 2 3 2.5
3 2015 0 4 3 6 4.33
4 2014 3 2 4 0 2.25
Would appreciate your help on this.