2010-10-14 53 views
15

我正在嘗試編寫交互式R腳本。例如:如何在腳本中包含交互輸入以便從命令行運行

try.R:現在

print("Entr some numbers. >",quote=F) 
a = scan(what=double(0)) 
print a 
q() 

,如果我在命令行中運行它

$ R --no-save < try.R 

它試圖擺脫try.R標準輸入,給予以下錯誤:

> print("Entr some numbers. >",quote=F) 
[1] Entr some numbers. > 
> a = scan(what=double(0)) 
1: print a 
Error in scan(file, what, nmax, sep, dec, quote, skip, nlines, na.strings, : 
    scan() expected 'a real', got 'print' 
Execution halted 

我嘗試了其他一些方法,但他們都出現錯誤。例如:

$ R CMD BATCH try.R 
$ Rscript try.R 

那麼,如何編寫的R腳本,從* nix的shell命令行工作,並且可以從用戶在交互式輸入走?

回答

19

試試這個:

cat("What's your name? ") 
x <- readLines(file("stdin"),1) 
print(x) 

希望的一些變種爲你工作。

+2

IIRC只是'readlines方法(N = 1)'應該做太多。 – 2010-10-14 16:47:47

+0

@Dirk Eddelbuettel:這似乎並不奏效。 – highBandWidth 2010-10-14 16:52:25

+1

我的不好,抱歉。我偶然使用'readLines()'而沒有文件參數,默認爲stdin,同時 - 從今天早上開始看到r-help。 – 2010-10-14 17:38:49

5

什麼用RStudio 0.98.945和R版本3.1.1爲我工作在Windows是:

cat("What's your name? ") 
    x <- readLines(con=stdin(),1) 
    print(x) 
相關問題