简体   繁体   English

function 在 R 中生成 NA

[英]function generating NA in R

I need help, my function not work correctly when i try make any sum with the results.我需要帮助,当我尝试对结果求和时,我的 function 无法正常工作。 have a lot of NA values and I don't know why.有很多 NA 值,我不知道为什么。

Craps <- function(jogadas){
   for (i in 1:jogadas){
    
    comeOut <- sample(1:6,1)+ sample(1:6,1)
    
    if(comeOut %in% c(2,3,12)){
      
      result <- F #False
      
    }else if(comeOut %in% c(7,11)){
      
      
    }
    else{
      
      dados <- sample(1:6,1) + sample(1:6,1)
      
      if(dados == 7){
        result <- F
      }else {
        result <- T
      }
      while (!(dados %in% c(7,comeOut))){
        dados <- sample(1:6,1)+ sample(1:6,1)
        
      }
      if(dados == 7)
        result <- F
        
      else result <- T
     
    }
    print(result)
    #probability
    prob<-NULL
    prob[i] <- result
    prob2<-sum(prob)/jogadas
    print(prob2)
   }  
  }
Craps(1000)

You put prob=NULL inside your loop, so it will become NULL at each iteration of the loop, just create prob before the loop.您将prob=NULL放入循环中,因此在循环的每次迭代中它将变为 NULL ,只需在循环之前创建prob Also you forgot one line as noticed in the comments:您还忘记了评论中注意到的一行:

Craps <- function(jogadas){
  prob<-NULL
  for (i in 1:jogadas){
    
    comeOut <- sample(1:6,1)+ sample(1:6,1)
    
    if(comeOut %in% c(2,3,12)){
      
      result <- F #False
      
    }else if(comeOut %in% c(7,11)){
      result <- T
      
    }
    else{
      
      dados <- sample(1:6,1) + sample(1:6,1)
      
      if(dados == 7){
        result <- F
      }else {
        result <- T
      }
      while (!(dados %in% c(7,comeOut))){
        dados <- sample(1:6,1)+ sample(1:6,1)
        
      }
      if(dados == 7)
        result <- F
      
      else result <- T
      
    }
    print(result)
    #probability
    
    prob[i] <- result
    prob2<-sum(prob)/jogadas
    print(prob2)
  }  
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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