Error with Nested for Loops

library(tidyverse)
library(reprex)

# 0 women
# 1 men

actual <- c(0, 2, 3, 0, 4, 3, 2, 2)

students <- rep(0, 4*length(actual) - sum(actual)) %>% 
  append(rep(1, sum(actual)))

results <- c()
trial <- c()

for (i in 1:500) {
  for (f in length(actual)) {
  temp <- sample(students, 4, replace = FALSE)
  trial[f] <- sum(temp, na.rm = TRUE)
  }
  results[i] <- var(trial)
  trial <- c()
}

Created on 2020-02-12 by the reprex package (v0.3.0)

Do you mean

for (f in 1:length(actual))

in the second for loop? If you use (f in length(actual)) you only get one iteration of the loop.

1 Like

You can also use seq_along(actual)

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.