2014-07-15 120 views
2

我想了解在執行Rscript時從STDIN讀取時會發生什麼情況。從stdin中讀取R時出現奇怪的行爲

首先,我有我要讀入R上的數據文件:

[email protected] testscripts # cat rdata 
5 7 

這是我第RSCRIPT,

a <- scan(file="stdin", what=integer(0), n=1); 
b <- scan(file="stdin", what=integer(0), n=1); 

導致此行爲:

[email protected] testscripts # Rscript ../rscripts/ttest.r < rdata 
Read 1 item 
Read 0 items 
[email protected] testscripts # cat rdata | Rscript ../rscripts/ttest.r 
Read 1 item 
Read 0 items 

在這一點上,我已經感到困惑,至於爲什麼只有一個值被讀取。我一直在試圖找到關於scan函數的更多信息,但我找不到任何可以解釋這一點的內容。

如果我改變RSCRIPT爲以下,

sin <- file("/dev/stdin"); 
a <- scan(sin, what=integer(0), n=1); 
b <- scan(sin, what=integer(0), n=1); 

我得到這樣的結果,而不是:

[email protected] testscripts # Rscript ../rscripts/ttest.r < rdata 
Read 1 item 
Read 1 item 
[email protected] testscripts # cat rdata | Rscript ../rscripts/ttest.r 
Read 0 items 
Read 0 items 

這使我更加困惑,我的結果應該是等價的。最後,如果我嘗試這個命令:

[email protected] testscripts # cat rdata > tmp; Rscript ../rscripts/ttest.r < tmp 
Read 1 item 
Read 1 item 

我得到預期的行爲。有人可以向我解釋發生了什麼事嗎?爲什麼R不能以流方式讀取數據?

+0

嘗試使用'標準輸入()'來指向'stdin' – Andrie

回答

1

當你調用scan"stdin"作爲輸入,它在一次讀取整個標準輸入,即使你只是它僅限於一個字符。第二次調用它時,什麼都沒有了,所以它什麼都不返回。

如果要讀取stdin「一次一個」,則可以使用具有「讀取」模式集的文件連接。如果你讓你的ttest.r腳本這樣的:

con=file("stdin", "r") 
scan(file=con, what=integer(0), n=1) 
scan(file=con, what=integer(0), n=1) 

然後你從你的shell撥打:

Rscript ttest.r < rdata 
# Read 1 item 
# [1] 5 
# Read 1 item 
# [1] 7  

我有點困惑,爲什麼你不會得到同樣的事情我試圖管道的其他方式:

cat rdata | Rscript ttest.r 
# Read 1 item 
# [1] 5 
# Read 1 item 
# [1] 7 
+0

謝謝您的回覆,unfort unaly我得到了同樣的問題,因爲我在我的帖子descibed。如果我運行命令'cat rdata | Rscript ../ rscripts/ttest.r'仍然讀取0個項目。 – Hasofanten

+0

如果你交互地打開'R',運行'con = file(「rdata」,「r」)',然後兩個'scan'命令是否工作? – nograpes

+0

不,我得到以下輸出:'掃描錯誤(文件,什麼,nmax,sep,dec,引號,skip,nlines,na.strings,: scan()預期'一個整數',掃描= con,'' – Hasofanten

相關問題