我在R中的“重复”功能有问题

问题描述 投票:0回答:1

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个回答
0
投票

我看到您的代码有几个问题。我们将专注于您为播放器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=<-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}
© www.soinside.com 2019 - 2024. All rights reserved.