T.Omalley
T.Omalley

Reputation: 345

mean average at every point

Dput data

df <- structure(list(Log_Score = c(1.02036009176836, 1.04731899428056, 
1.26147129638715, 2.01321383095142, 1.21566884408913, 1.04241773032447
), Time_Stamp = 1:6, Time_Log_Mean = c(0, 0, 0, 0, 0, 0)), row.names = c(NA, 
-6L), class = c("tbl_df", "tbl", "data.frame"))
> df
# A tibble: 6 x 3
  Log_Score Time_Stamp Time_Log_Mean
      <dbl>      <int>         <dbl>
1      1.02          1             0
2      1.05          2             0
3      1.26          3             0
4      2.01          4             0
5      1.22          5             0
6      1.04          6             0

I am trying to create a mean average for every point in time using a for loop but can't seem to get it to work. The code I was using is:

for (i in 1:nrow(df)) {
    df$Time_Log_Mean[i] <- ((sum(df$Log_Score[1:i]))/(df$Time_Stamp[i]))
}

The code has mysteriously started to work after initial giving me the error message:

Assigned data value must be compatible with existing data. x Existing data has 335 rows. x Assigned data has 6553 rows. i Only vectors of size 1 are recycled.

Upvotes: 0

Views: 31

Answers (1)

Yuriy Saraykin
Yuriy Saraykin

Reputation: 8880

looks like a cumulative average calculation

df <-
  structure(
    list(
      Log_Score = c(
        1.02036009176836,
        1.04731899428056,
        1.26147129638715,
        2.01321383095142,
        1.21566884408913,
        1.04241773032447
      ),
      Time_Stamp = 1:6,
      Time_Log_Mean = c(0, 0, 0, 0, 0, 0)
    ),
    row.names = c(NA,-6L),
    class = c("tbl_df", "tbl", "data.frame")
  )

library(tidyverse)
df %>% 
  mutate(res = cummean(Log_Score))
#> # A tibble: 6 × 4
#>   Log_Score Time_Stamp Time_Log_Mean   res
#>       <dbl>      <int>         <dbl> <dbl>
#> 1      1.02          1             0  1.02
#> 2      1.05          2             0  1.03
#> 3      1.26          3             0  1.11
#> 4      2.01          4             0  1.34
#> 5      1.22          5             0  1.31
#> 6      1.04          6             0  1.27

Created on 2022-04-25 by the reprex package (v2.0.1)

Upvotes: 1

Related Questions