Hi All,
I stumbled upon this post while learning R: https://r.789695.n4.nabble.com/Loop-with-variable-index-td845011.html
The qustion was as follows: " 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? "
And two answers were presented:
- Solution, which I personnaly think is brilliant:
x <- rnorm(20)
sapply(c("sd", "mean"), function(fun)lapply(lapply(lapply(2:20, seq,
from=1), function(.x)x[.x]), fun))
But trying to understand the code I am stuck:
Generally I understand what "for loops" are made for but I was able to break it down only into this:
lapply(2:20, seq, from=1)
So I would like to understand how all that code works and why there are three lapplies in a row in it ? What do those " (.x), [.x] " mean, and how is it possible to recreate it in tidyverse maybe in a simpler way ?
- Solution:
Let the vector be ``x''.
mns <- list()
sds <- list()
for(i in 2:20) {
mns[[i-1]] <- mean(x[1:i])
sds[[i-1]] <- sd(x[1:i])
}
mns <- unlist(mns)
sds <- unlist(sds)
which I try to understand as well, especially subsetting in here like: " mns[[i-1]] ", because sometimes in loops we have " vec[i] ", or " vec[[i]] ".
And finally why here:
mns[[i-1]] <- mean(x[1:i])
on the left hand side of an assignment arrow, we have "i-1" in brackets and on the right hand side of <- we have "x[1:i]" ? What does it do ?
Any help regarding how to understand it correctly would be much appreciated.
Thank you in advance.