【问题标题】:How can I bring out a variable that has been saved inside a function in R?如何带出已保存在 R 函数中的变量?
【发布时间】:2020-08-16 09:26:14
【问题描述】:

我制作了一个询问用户姓名的代码,但我希望我的代码保存这个名称(当我输入“name1”时,代码应该告诉我用户在“name1”中输入了什么)。这是我的代码:

checknames <- function(){
  gamers <- c("Rebeca","Lucas","Mario")
  games <- c("3","1","3")
  scores <- c("200","100","205")
  table <- data.frame(gamers,games,scores)
  r=0
  name1 <- c()
  repeat{
    print("Name Player 1: ")
    name1=scan(,what="character",1)
    for(i in 1:length(gamers)){
      if(name1==gamers[i]){
        print("This player is already in the file. Would you like to change the name?")
        r=scan(,what="character",1)
      }
    }
    if(r==2){
      break
    }
    if(r==0){
      gamers=c(gamers,name1)
      name1 <- data.frame(gamers=name1,games="0",scores="100")
      table1 <- rbind(table,name1)
      print("Nice")
      break
    }
  }
}
checknames()

希望你能帮助我。谢谢。

【问题讨论】:

  • 您希望如何调用它? checknames()第一次询问玩家,然后checknames()第二次返回之前识别的名字而不再次询问?
  • @Jiakai,下面的答案对你有用吗?

标签: r function return


【解决方案1】:

您的函数目前没有返回任何内容,并且每次运行它都会创建具有 3 行的相同数据框。如果您想要上传新玩家的数据框,那么您需要将其用作函数的输入:

gamers <- c("Rebeca","Lucas","Mario")
games <- c("3","1","3")
scores <- c("200","100","205")
df <- data.frame(gamers,games,scores) ### a data frame with previously-registered users

checknames <- function(table){

  r=0
  name1 <- c()
  repeat{
    print("Name Player 1: ")
    name1=scan(,what="character",1)
    for(i in 1:length(gamers)){
      if(name1==gamers[i]){
        print("This player is already in the file. Would you like to change the name?")
        r=scan(,what="character",1)
      }
    }
    if(r==2){
      break
    }
    if(r==0){
      gamers=c(gamers,name1)
      name1 <- data.frame(gamers=name1,games="0",scores="100")
      table1 <- rbind(table,name1)
      print("Nice")
      break
    }
  }
return (table1)} ### returns the input df with an added row

df <- checknames(df)

通过运行此程序,系统会提示您引入一个新名称,如果不重复,您的 df 将被重写为额外的行。

函数内部发生的任何事情都不会是永久的,除非函数返回它并分配它。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-12-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-04-14
    • 2021-10-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多