I experience some problems with the loop function in R and couldn’t find an answer on this question on this website. I would like to use a numeric vector as input for a loop in R.
For example:
ns <- c(10, 20, 40, 80, 160)
for (n in ns) {
ni[n] <- round(rnorm(1, mean = n, sd = 1))
}
The result of this code is a vector with 155 times NA and five correct values in this vector. However, I would like to get rid of all those NAs and get a vector with only the five correct values. I know how to select the correct values from the vector with the 155 NA, but I prefer to obtain a proper vector directly after running the loop.
Thank you in advance!
Remember that many functions in R are vectorized
(in your question,
ni[n]creates a vector as long as the maximum ofn, i.e., 160 elements).It’s interesting to see this evolve from an
sapplysolution offered by @VictorK.factor out the
roundand drop the default argumentsd = 1, sothen recognize that
rnormcould replace the anonymous functionfunction(n) ...if we name it’s first argument in thesapplycall. The first argument ofrnormis namedn, so things are a little confusing; but we’re forcing the elements ofnsto match the second argumentmean. For instance the first time through the sapply we evaluaternorm(ns[[1]], n=1). R matches arguments first by name, so n=1 matches the first argument ofrnorm, and then by position amongst the remaining arguments, so the unnamed argumentns[[1]]matches the next available argument,mean)and then perhaps we see the fully vectorized solution