Having Issue with my if statement for generating random ID numbers

if(yearincollege=="Freshman" &&lastnameletter==LETTERS[1:13]){
print(sample(2700000:2700900,1, replace=FALSE))
}else if (yearincollege=="Freshman" &&lastnameletter==LETTERS[14:26]){
print(sample(2701000:2709000,1, replace=FALSE))
}else if (yearincollege=="Sophomore" &&lastnameletter==LETTERS[1:13]){
print(sample(2710000:2790000,1, replace=FALSE))
}else if (yearincollege=="Sophomore" &&lastnameletter==LETTERS[14:26]){
print(sample(2800000:2890000,1, replace=FALSE))
}else if (yearincollege=="Junior" &&lastnameletter==LETTERS[1:13]){
print(sample(2900000:2900900, 1, replace=FALSE))
}else if (yearincollege=="Junior" &&lastnameletter==LETTERS[14:26]){
print(sample(2901000:2909000, 1, replace=FALSE))
print(sample(2910000:2910900, 1, replace=FALSE))

The problem with this code of mine is that it kept printing the number between 2910000 and 2910900 (which loops to else). I have "Sophomore" for the variable 'yearincollege' and the letter B (in the form of LETTERS[B]) for the variable 'lastnameletter'; those two variables should loop to sample numbers between 2710000 and 2790000. Any help would be appreciated!

Hi there,
Welcome to the RStudio Community Forum!
I think you need %in% instead of ==. I have replaced && with & and bracketed each condition.

yearincollege <- "Sophomore"
lastnameletter <- LETTERS[2]

if ((yearincollege %in% "Freshman") & (lastnameletter %in% LETTERS[1:13])) {
  print(sample(2700000:2700900, 1, replace = FALSE))
} else if ((yearincollege %in% "Freshman") &
           (lastnameletter %in% LETTERS[14:26])) {
  print(sample(2701000:2709000, 1, replace = FALSE))
} else if ((yearincollege %in% "Sophomore") &
           (lastnameletter %in% LETTERS[1:13])) {
  print(sample(2710000:2790000, 1, replace = FALSE))
} else if ((yearincollege %in% "Sophomore") &
           (lastnameletter %in% LETTERS[14:26])) {
  print(sample(2800000:2890000, 1, replace = FALSE))
} else if ((yearincollege %in% "Junior") &
           (lastnameletter %in% LETTERS[1:13])) {
  print(sample(2900000:2900900, 1, replace = FALSE))
} else if ((yearincollege %in% "Junior") &
           (lastnameletter %in% LETTERS[14:26])) {
  print(sample(2901000:2909000, 1, replace = FALSE))
} else {
  print(sample(2910000:2910900, 1, replace = FALSE))
# [1]  2787221


1 Like

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