Q: How to add a mean column based on user ID and session ID in R? I would like to ask a question regarding coding. 
I have datasets and it has a session Id, User Id, and the target column which is the sales each session.
Here is a sample of what I have 

dataset <- structure(list(ID = 1:8, USERID = c(500L, 520L, 500L, 530L, 530L, 
    520L, 520L, 520L), SALES = c(1000L, 1450L, 1390L, 1778L, 1966L, 
    1100L, 700L, 900L), Mean = c(1000, 1450, 1195, 1778, 1872, 1275, 
    1083.33, 1037.5)), row.names = c(NA, 8L), class = "data.frame")

My goal is to create a column for the mean for each session based on the specific user sessions. 
Thank you, 

A: This is easily done with group_by from dplyr together with cumsum:
library(dplyr)
dataset %>% 
  group_by(USERID) %>%
  mutate(Mean = cumsum(SALES)/(1:n()))
# A tibble: 8 x 4
# Groups:   USERID [3]
     ID USERID SALES  Mean
  <int>  <int> <int> <dbl>
1     1    500  1000 1000 
2     2    520  1450 1450 
3     3    500  1390 1195 
4     4    530  1778 1778 
5     5    530  1966 1872 
6     6    520  1100 1275 
7     7    520   700 1083.
8     8    520   900 1038.

dataset <- structure(list(ID = 1:8, USERID = c(500L, 520L, 500L, 530L, 530L, 
    520L, 520L, 520L), SALES = c(1000L, 1450L, 1390L, 1778L, 1966L, 
    1100L, 700L, 900L)), row.names = c(NA, 8L), class = "data.frame")


A: This works in base-R
dataset$Mean <- sapply(1:nrow(dataset), function(x) mean(dataset$SALES[1:x][dataset$USERID[1:x]==dataset$USERID[x]]))

  ID USERID SALES     Mean
1  1    500  1000 1000.000
2  2    520  1450 1450.000
3  3    500  1390 1195.000
4  4    530  1778 1778.000
5  5    530  1966 1872.000
6  6    520  1100 1275.000
7  7    520   700 1083.333
8  8    520   900 1037.500


A: We could also use data.table methods
library(data.table)
setDT(dataset)[, Mean := cumsum(SALES)/seq_len(.N), USERID]

data
dataset <- structure(list(ID = 1:8, USERID = c(500L, 520L, 500L, 530L, 530L, 
    520L, 520L, 520L), SALES = c(1000L, 1450L, 1390L, 1778L, 1966L, 
    1100L, 700L, 900L)), row.names = c(NA, 8L), class = "data.frame")

