Estimating probability with if condition using R

I'm trying simulation in R, I want to check the probability of the person getting caught with the number of students is 40. but I get this error, Error in if (caught == "TRUE") { : the condition has length > 1. What does this error mean? How can I correct this error? TIA

#Initialise number of students 1:40 
num_of_students <- c(1:40)

#Calculate number of exams tested - round(sqrt(length(number of students)))
num_of_exams_tested <- round(sqrt(length(num_of_students)))

#Initialise caught counter
caught_counter <- 0;

for(i in 10000){
  examschecked <- sample(num_of_students, num_of_exams_tested)
#the person didn't read the paper for every 10th student
  examsunmarked <- examschecked/10
 #The examiner will identify an unmarked exam correctly 94% of the time 
  for(i in examsunmarked) {
    caught <- sample(c("TRUE", "FALSE"), prob = c(0.94, 0.06))
    if(caught == "TRUE"){
      caught_counter <- caught_counter + 1;
    return (caught_counter)
print((caught_counter/10000) * 100)

The error means that the condition tested in the if() has a length greater than 1, i.e. caught == "TRUE" has a length greater than one. If you run

caught <- sample(c("TRUE", "FALSE"), prob = c(0.94, 0.06))

by itself, you will see that it returns two values. Change it to

caught <- sample(c("TRUE", "FALSE"), prob = c(0.94, 0.06), size = 1)

and the error will not occur.

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

If you have a query related to it or one of the replies, start a new topic and refer back with a link.