lundi 6 août 2018

R: For loop only updating last element in vector

The logic I've followed is;

-> create a results vector with 1000 elements

-> Use a for loop that on each iteration will replace the old sample value "sorting_hat" with a new value

-> Use a if else statement to replace the i'th iteration in the results vector with a string that's dependent on the new sampled value "sorting_hat"

all_student_houses <- rep(0, 1000)
total_students = 1000
student_number = 1


for (student_number in total_students) {

  sorting_hat <- sample(x = 1:4, size = 1, replace = TRUE, prob = c(9/41, 8/41, 14/41, 10/41) )

  if (sorting_hat == 1) {
    all_student_houses[student_number] <- "Slytherin"
    } else if (sorting_hat == 2) {
    all_student_houses[student_number] <- "Gryffindor"
    } else if (sorting_hat == 3) {
    all_student_houses[student_number] <- "Ravenclaw"
    } else {
    all_student_houses[student_number] <- "Hufflepuff"
    }

  }

My vectors output after running this is:

>all_student_houses
[995] "0"         "0"         "0"         "0"         "0"         "Slytherin"

I'd expect every element of this vector to be replaced by one of the four strings in the ifelse statement, not just the last element. What is currently tripping me up?

Aucun commentaire:

Enregistrer un commentaire