LoslegenKostenlos loslegen

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.

Diese Übung ist Teil des Kurses

Parallel Programming in R

Kurs anzeigen

Interaktive Übung

Versuche dich an dieser Übung, indem du diesen Beispielcode vervollständigst.

# Specify input to loop over 
at_risk_perc <- foreach(m = ___
                        # Specify the sequential operator
                       ) ___ {
  sum(m > 35 | m < 20) * 100/length(m)}
Code bearbeiten und ausführen