Sample code to loop functions in R
New here? Learn about Bountify and follow @bountify to get notified of new bounties! x

I have a small data frame with 51 observations and 2 variables. I would like to create a series of loops to perform the following tasks a total of 56 times:

1) For each NUMBER, replace the value with its current value plus a GLOBAL draw from a normal distribution of mean 0 and sd 0.002, plus an INDIVIDUAL draw from a normal distribution of mean 0 and sd 0.001.


2) Conduct that operation 44 times consecutively, with the new NUMBER forming the basis for the subsequent loop. The GLOBAL draw should be the same for each observation within an iteration, but should change across each iteration. So, with the sample data below, in the first iteration, Ed, Mary, William, and Mike should all have different INDIVIDUAL draws added to their value, but the same GLOBAL draw. For the next iteration, a new GLOBAL draw should be added to Ed, Mary, William, and Mike's values, along with yet another INDIVIDUAL draw for each.

After the 44th iteration, the data frame should have a new NUMBER for each row, having been changed 44 times over the course of the process.

GLOBAL <- rnorm(1, 0, 0.002)
INDIV <- rnorm(1, 0, 0.001)


Ed, 25.5

Mary, 23.6

William, 22.1

Mike, 23.4

Please provide code when finished.

awarded to codecustard

Crowdsource coding tasks.

1 Solution

Winning solution

name <- c("Ed", "Mary", "William", "Mike")
number <- c(25.5, 23.6, 22.1, 23.4)
observation <- data.frame(name, number)

#Number of times to repeat
repeatCount <- 56
GLOBAL <- rnorm(repeatCount, 0, 0.002)

for (r in 1:repeatCount) {
    INDIV <- rnorm(dim(observation)[1], 0, 0.001)
    for (i in 1 : dim(observation)[1]) {
        observation$number[i] <- observation$number[i] + GLOBAL[r] + INDIV[i]