【问题标题】:R - for loop error: "Unexpected '}' in '}'"R - for循环错误:“'}'中的意外'}'”
【发布时间】:2020-09-03 16:26:39
【问题描述】:

这是我尝试运行的模拟代码:

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

 }
}

基本上,我想将 1 添加到相应的列表中,条件是该数字在 (0,1) 范围内的位置。我不确定为什么这会出错。有什么建议吗?

【问题讨论】:

    标签: r for-loop if-statement simulation


    【解决方案1】:

    您只是在cutoff[3] 之后缺少一个右括号,在我的示例中也使用了seq_along,因为它更好一点

    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
        
      }
    }
    

    【讨论】:

    • 太棒了,谢谢!我之前没有听说过seq_along,所以我会检查一下
    猜你喜欢
    • 1970-01-01
    • 2018-03-24
    • 2011-06-21
    • 1970-01-01
    • 2020-06-06
    • 2018-05-08
    • 2017-10-07
    • 1970-01-01
    相关资源
    最近更新 更多