【问题标题】:I have a problem with a "repeat" function in R我对 R 中的“重复”功能有疑问
【发布时间】:2020-04-28 11:39:46
【问题描述】:

checknames <- function(){
  gamers <- c("Rebeca","Luis","Paco")
  games <- c("3","2","7")
  scores <- c(100,110,50)
  table <- data.frame(gamers,games,scores)
  r=0
  p=0
  repeat{
    print("Name Player 1: ")
    name1=scan(,what="character",1)
    for(i in 1:length(gamers)){
      if(name1==gamers[i]){
        r=readline(prompt = "This player is already in the file. Would you like to change the name? \n 1. Yes \n 2. No \n Select an option: ")
      }
    }
    if(r==2){
      break
    }
    if(r==0){
      gamers=c(gamers,name1)
      name1 <- data.frame(gamers=name1,games="1",scores="100")
      table <- rbind(table,name1)
      break
    }
  }
  table
  repeat{
    print("Name Player 2: ")
    name2=scan(,what="character",1)
    for(i in 1:length(gamers)){
      if(name2==gamers[i]){
        print("This player is already in the file. Would you like to change the name?")
        r=scan(,what="character",1)
      }
    }
    if(p=="No"){
      break
    }
    if(p==0){
      gamers=c(gamers,name2)
      name2 <- data.frame(gamers=name2,games="1",scores="100")
      table <- rbind(table,name2)
      break
    }
  }
  table
}
table <-checknames()

我正在编写一个询问用户 2 个名称的代码,它应该证明表是否有这个名称,如果没有,添加它,如果有这个名称,询问玩家他/她是否想要改变它。

问题是当玩家说他想改变名字时,重复功能永远不会中断,我认为那是因为我分配了错误(我分配了r==2/r==0)这就是为什么重复功能仍在重复。

【问题讨论】:

    标签: r


    【解决方案1】:

    我发现您的代码存在一些问题。我们将专注于您为玩家 2 编写的第二个 repeat 循环。

    首先,我们可以简化用于检查名称是否已被占用的for(if( 循环。通过一次检查所有列表而不是遍历整个索引。

    if(any(name2==gamers)){
            print("This player is already in the file. Would you like to change the name?")
            r=scan(,what="character",1)
          }
    

    现在,继续解决您的一些问题。您将变量 r 存储在扫描中,但您正在检查变量 p。您应该将上述代码块中的行更改为p=scan(,what="character",1)。

    此外,您现在遇到的情况是,如果您的 user2 输入了一个已经使用的名称,然后将其更改为其他名称,您的代码将永远不会让它们泄露出去,因为您从未将 p 设置回 0 .这可以通过添加else { p=&lt;-0 } 行来解决。

    以上所有更改都在这里为您汇总:

    if(any(name2==gamers)){
            print("This player is already in the file. Would you like to change the name?")
            p=scan(,what="character",1)
          } else {
            p <- 0}
    

    【讨论】:

    猜你喜欢
    • 2021-12-01
    • 1970-01-01
    • 2020-09-19
    • 2021-01-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-10
    相关资源
    最近更新 更多