[R] Loop with variable index
Benilton Carvalho
bcarvalh at jhsph.edu
Wed Jan 30 21:36:18 CET 2008
a cleaner code would be:
sapply(2:20, function(i) c(mean=mean(x[1:i]), sd=sd(x[1:i])))
b
On Jan 30, 2008, at 3:16 PM, Henrique Dallazuanna wrote:
> Try this:
>
> x <- rnorm(20)
>
> sapply(c("sd", "mean"), function(fun)lapply(lapply(lapply(2:20, seq,
> from=1), function(.x)x[.x]), fun))
>
> On 30/01/2008, cvandy <cvandy26 at gmail.com> wrote:
>>
>> I have a list of 20 values. The first time through a loop I want
>> to find the
>> mean and stnd.dev. of the first two values; the second time through
>> the loop
>> I want to find the mean and stnd. dev. of the first 3 values, etc.
>> until
>> the last time through the loop I want to find the mean and stnd.
>> dev. of all
>> 20 values, so I end up with 19 means and stnd. deviations.
>> How would I construct such a loop?
>> Thanks.
>> --
>> View this message in context: http://www.nabble.com/Loop-with-variable-index-tp15190661p15190661.html
>> Sent from the R help mailing list archive at Nabble.com.
>>
>> ______________________________________________
>> R-help at r-project.org mailing list
>> https://stat.ethz.ch/mailman/listinfo/r-help
>> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
>> and provide commented, minimal, self-contained, reproducible code.
>>
>
>
> --
> Henrique Dallazuanna
> Curitiba-Paraná-Brasil
> 25° 25' 40" S 49° 16' 22" O
>
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
More information about the R-help
mailing list