2014-10-30 54 views
2

我發現了一個(可能已知的)問題。當您嘗試在while循環中使用Sys.sleep時,它不起作用。具體來說,它要麼等待所有的聯合睡眠,然後一次打印或短時間噴射。R Sys.sleep打印不能在while循環中工作

示例代碼:

i1 <- 0 
while (i1 < 3) { 
i1 <- i1 + 1 
print(1) 
Sys.sleep(1) 
print(2) 
Sys.sleep(1) 
print(3) 
Sys.sleep(1) 
print("GO!") 
} 

任何想法,變通或解決方案? (除了不使用循環...)

謝謝!

+0

爲我工作。發佈會話信息?另外,你是否可以描述「短暫噴發」? – Gregor 2014-10-30 01:03:27

+0

「short spurts」我的意思是它將運行3或4行代碼 - 然後等待3或4秒,然後運行下一個3或4等。與打印1行相反,等待1秒,打印下一行等 – jdfinch3 2014-10-30 01:14:40

+1

我懷疑你的標準輸出緩衝,只有稍後打印。爲了測試這個理論,你可以使用'op < - options(digits.secs = 6)'然後'print(Sys.time())'而不是'print(1)','print(2)'等。也許一切都會在最後同時印刷,但時間戳會相隔一秒。 – flodel 2014-10-30 01:18:02

回答

3

在右的Windows和OS X的圖形用戶界面,你將需要使用flush.console()避免正是您所描述的行爲:

i1 <- 0 
while (i1 < 3) { 
    i1 <- i1 + 1 
    print(1); flush.console() 
    Sys.sleep(1) 
    print(2); flush.console() 
    Sys.sleep(1) 
    print(3); flush.console() 
    Sys.sleep(1) 
    print("GO!"); flush.console() 
} 
+0

謝謝!這工作完美。 也感謝Gavin最初建議這條路線 - 我只是沒有正確實施它。 – jdfinch3 2014-10-30 03:26:20

+0

我試圖使用循環來檢查文件,直到完成整個循環,但連接聲音不穩定。 http://i.imgur.com/VCIMIvA.jpg – 2017-01-01 13:13:33