I'm new in R. Hoping someone could help me.
I am trying to get the mean using for the first values of i for nth iteration, example (first value on first iteration then first two values on 2nd iterations)
How do I go about doing this?
Here is the sample data:
set.seed(1234)
i <- sample(200,100)
CodePudding user response:
An alternative, may be, simpler solution
set.seed(1234)
i <- sample(200,100)
cumsum(i)/(1:100)
#> [1] 28.00000 54.00000 86.00000 89.75000 94.00000 101.16667 105.71429
#> [8] 113.25000 116.66667 118.20000 116.36364 115.25000 113.30769 110.21429
#> [15] 108.13333 108.62500 103.05882 104.33333 102.10526 97.20000 101.66667
#> [22] 103.81818 101.04348 100.70833 101.56000 105.11538 103.66667 105.96429
#> [29] 106.55172 104.60000 104.70968 105.53125 104.96970 103.08824 103.42857
#> [36] 102.55556 104.10811 102.47368 100.94872 98.47500 98.92683 101.00000
#> [43] 99.79070 99.84091 98.75556 99.52174 100.76596 101.87500 100.95918
#> [50] 101.66000 100.17647 101.03846 102.37736 100.62963 100.54545 99.14286
#> [57] 98.01754 99.20690 100.38983 100.15000 101.00000 99.53226 99.68254
#> [64] 100.34375 100.07692 101.39394 100.17910 99.75000 99.18841 99.85714
#> [71] 100.35211 100.72222 102.04110 101.02703 100.69333 101.53947 102.44156
#> [78] 101.89744 101.43038 100.61250 100.83951 102.04878 101.04819 99.95238
#> [85] 99.12941 98.70930 97.77011 98.44318 98.92135 98.46667 97.45055
#> [92] 97.31522 97.75269 97.05319 96.84211 97.02083 97.81443 97.93878
#> [99] 98.92929 99.55000
Created on 2022-03-04 by the reprex package (v2.0.1)
CodePudding user response:
Here's a one-liner to get the result:
sapply(1:100, function(x) mean(i[seq(x)]))
#> [1] 28.00000 54.00000 86.00000 89.75000 94.00000 101.16667 105.71429
#> [8] 113.25000 116.66667 118.20000 116.36364 115.25000 113.30769 110.21429
#> [15] 108.13333 108.62500 103.05882 104.33333 102.10526 97.20000 101.66667
#> [22] 103.81818 101.04348 100.70833 101.56000 105.11538 103.66667 105.96429
#> [29] 106.55172 104.60000 104.70968 105.53125 104.96970 103.08824 103.42857
#> [36] 102.55556 104.10811 102.47368 100.94872 98.47500 98.92683 101.00000
#> [43] 99.79070 99.84091 98.75556 99.52174 100.76596 101.87500 100.95918
#> [50] 101.66000 100.17647 101.03846 102.37736 100.62963 100.54545 99.14286
#> [57] 98.01754 99.20690 100.38983 100.15000 101.00000 99.53226 99.68254
#> [64] 100.34375 100.07692 101.39394 100.17910 99.75000 99.18841 99.85714
#> [71] 100.35211 100.72222 102.04110 101.02703 100.69333 101.53947 102.44156
#> [78] 101.89744 101.43038 100.61250 100.83951 102.04878 101.04819 99.95238
#> [85] 99.12941 98.70930 97.77011 98.44318 98.92135 98.46667 97.45055
#> [92] 97.31522 97.75269 97.05319 96.84211 97.02083 97.81443 97.93878
#> [99] 98.92929 99.55000
Created on 2022-03-04 by the reprex package (v2.0.1)