简体   繁体   中英

R - for loop error: “Unexpected '}' in '}'”

here is the code for a simulation I'm trying to run:

n_draws <- 1000

black <- rep(0, n_draws)
hispanic <- rep(0, n_draws)
asian <- rep(0, n_draws)
white <- rep(0, n_draws)


cutoff <- c(0.05,0.1,0.25,1)
draws <- runif(n_draws,0,1)

for (i in draws){
  
  if (draws[i] < cutoff[1]){
    
    black[i] <- 1
    
  } else if ((draws[i] >= cutoff[1]) & (draws[i] < cutoff[2])){
    
    hispanic[i] <- 1
    
  } else if ((draws[i] >= cutoff[2]) & (draws[i] < cutoff[3]){
    
    asian[i] <- 1
    
  } else {

white[i] <- 1

 }
}

Basically, I want to add a 1 to the corresponding list, conditional on where that number falls in the range (0,1). I'm not sure why this is giving an error. Suggestions?

You're just missing a closing bracket just after cutoff[3] , also used seq_along in my example as it's a bit nicer

for (i in seq_along(draws)){
  
  if (draws[i] < cutoff[1]){
    
    black[i] <- 1
    
  } else if ((draws[i] >= cutoff[1]) & (draws[i] < cutoff[2])){
    
    hispanic[i] <- 1
    
  } else if ((draws[i] >= cutoff[2]) & (draws[i] < cutoff[3])){
    
    asian[i] <- 1
    
  } else {
    
    white[i] <- 1
    
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM