2017-09-08 8 views
0

Rで整数ユーザーの入力を受け取り、以前のユーザー入力に追加するプログラムを作成したいとします。例。ユーザー入力(例えば1日):10、次に(おそらく翌日)ユーザー入力:15 - >出力25.これはほぼ無限の量の入力を受け入れることになります。ここで私がこれまで持っているものです。このコードで私が持っているRプログラムでお金を追加する

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()で操作できるデータにユーザー入力を保存する方法はありますか?

答えて

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) 
} 

あなたは、このようなスクリプトを実行する必要があります。ループのUnixでプレスCtrl-D、またはWindowsでのCtrl-Zを終了するにはRscript 1.R

0

これを行うためのR-ish方法は、クロージャによるものです。インタラクティブな使用の例(Rセッション内) balance_setupを呼び出す

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と2つの関数を作成しますバランスを変更するための1、それを印刷するための1。 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でループをブレイクエスケープか、ご使用のプラットフォーム上で使用されているものは何でも

関連する問題