1. Learn
  2. /
  3. Courses
  4. /
  5. Parallel Programming in R

Exercise

Looping with foreach

The US Department of Health has received reports of a higher rate of adverse outcomes during childbirth. You want to investigate if this trend is due to low or high maternal age. Your team has sourced the births dataset for the preceding year. You have a list, ls_age. Each element of this list is a vector of mother's age for every birth recorded in a US state.

The following loop calculates the percentage of births in a state where the maternal age is less 20 or greater than 35:

at_risk_perc <- rep(NA, length(ls_age))

for (m in 1:length(ls_age)) {
  at_risk_perc[m] <- 
    sum(ls_age[[m]] > 35 | ls_age[[m]] < 20) * 100/length(ls_age[[m]])
}

This is taking too long though, and you want to test other options. foreach, parallel, and doParallel have been loaded for you.

Instructions 1/2

undefined XP
    1
    2
  • Specify the inputs to loop over for the foreach() function.
  • Use the correct operator for sequential execution.