R

时间:2017-09-08 04:25:19

标签: r

我想在R中创建一个程序,它接受整数用户输入,然后将其添加到以前的用户输入。恩。用户输入(比如说一天):10,然后(可能是第二天)用户输入:15 ​​ - >输出25.Ideally这将接受几乎无限量的输入。这是我到目前为止:

amount_spent <- function(){
    i <-1
    while(i<10){
        n <- readline(prompt="How much did you spend?: ")
        i<-i+1
    }
print(c(as.integer(n)))
}
amount_spent()

我对此代码的问题是它只保存了最后一个输入值,并且很难控制何时允许用户输入。有没有办法将用户输入保存到可以通过readline()操作的数据?

2 个答案:

答案 0 :(得分:0)

# 1.R
fname <- "s.data"

if (file.exists(fname)) {
  load(fname)
}

if (!exists("s")) {
  s <- 0
}

n <- 0
while (TRUE) {
  cat ("Enter a number: ")
  n <- scan("stdin", double(),  n=1, quiet = TRUE)
  if (length(n) != 1) {
    print("exiting")
    break
  }
  s <- s + as.numeric(n)
  cat("Sum=", s, "\n")
  save(list=c("s"), file=fname)
}

您应该运行如下脚本:Rscript 1.R

要退出循环,请在Unix中按Ctrl-D,或在Windows中按Ctrl-Z

答案 1 :(得分:0)

R-ish的方法是通过闭包。以下是交互式使用的示例(即在R会话中)。

balance_setup <- function() {
    balance <- 0
    change_balance <- function () {
        n <- readline(prompt = "How much did you spend?: ")
        n <- as.numeric(n)
        if (!is.na(n))
            balance <<- balance + n
        balance
    }
    print_balance <- function() {
        balance
    }
    list(change_balance = change_balance,
         print_balance = print_balance)

}

funs <- balance_setup()
change_balance <- funs$change_balance
print_balance <- funs$print_balance

调用balance_setup创建一个变量balance和两个可以访问它的函数:一个用于更改余额,一个用于打印它。在R中,函数只能返回一个值,因此我将这两个函数捆绑在一起作为列表。

change_balance()
## How much did you spend? 5
## [1] 5

change_balance()
## How much did you spend? 5
## [1] 10

print_balance()
## [1] 10

如果您需要许多输入,请使用循环:

repeat{
    change_balance()
}

使用Ctrl-C,Escape或平台上使用的任何内容打破循环。

相关问题