0

I am trying to make a new data frame that contains the mean of a binary variable. For instance, I have:

Win Average
1 1
1 1
0 0.66
0 0.5
0 0.4
1 0.5
0 .42

On the "Win" category, I have some 500 entries. I am looking to build a new column like "Average" that calculates the average of the entry in the "Win" column up to that point -- not the average of the "Win" category completely. So an entry in row number 56 will calculate the average Win Rate from column 1 to 56 and populate it in the corresponding row.

BigBen
  • 46,229
  • 7
  • 24
  • 40
Buckethead
  • 31
  • 4

1 Answers1

0
(df_1 <- data.frame(
  win=c(1,0,1,1,0,1)
))


library(tidyverse)

df_1 |> mutate(
  cumwin=cumsum(win),
  nrow=row_number(),
  avg_win = cumwin/nrow
)

credit to Mael it could have been more directly

df_1 |> mutate(
  avg_win = cummean(win)
)
Nir Graham
  • 2,567
  • 2
  • 6
  • 10