nnn*_*nnn 104
正如有人已在评论中写道,您不必使用之前的猫readline().只需写:
readline(prompt="Press [enter] to continue")
Run Code Online (Sandbox Code Playgroud)
如果您不想将其分配给变量并且不希望在控制台中打印返回,请将其包装readline()在invisible():
invisible(readline(prompt="Press [enter] to continue"))
Run Code Online (Sandbox Code Playgroud)
Con*_*ngo 74
方法1
等待直到您在控制台中按[enter]:
cat ("Press [enter] to continue")
line <- readline()
Run Code Online (Sandbox Code Playgroud)
包装成功能:
readkey <- function()
{
cat ("Press [enter] to continue")
line <- readline()
}
Run Code Online (Sandbox Code Playgroud)
这个函数是Console.ReadKey()C#中最好的函数.
方法2
暂停,直到您在键盘上键入[enter]键.此方法的缺点是,如果键入的内容不是数字,则会显示错误.
print ("Press [enter] to continue")
number <- scan(n=1)
Run Code Online (Sandbox Code Playgroud)
包装成功能:
readkey <- function()
{
cat("[press [enter] to continue]")
number <- scan(n=1)
}
Run Code Online (Sandbox Code Playgroud)
方法3
想象一下,在绘制图表上的另一个点之前,您想要等待按键.在这种情况下,我们可以使用getGraphicsEvent()来等待图中的按键.
该示例程序说明了这一概念:
readkeygraph <- function(prompt)
{
getGraphicsEvent(prompt = prompt,
onMouseDown = NULL, onMouseMove = NULL,
onMouseUp = NULL, onKeybd = onKeybd,
consolePrompt = "[click on graph then follow top prompt to continue]")
Sys.sleep(0.01)
return(keyPressed)
}
onKeybd <- function(key)
{
keyPressed <<- key
}
xaxis=c(1:10) # Set up the x-axis.
yaxis=runif(10,min=0,max=1) # Set up the y-axis.
plot(xaxis,yaxis)
for (i in xaxis)
{
# On each keypress, color the points on the graph in red, one by one.
points(i,yaxis[i],col="red", pch=19)
keyPressed = readkeygraph("[press any key to continue]")
}
Run Code Online (Sandbox Code Playgroud)
在这里,您可以看到图表,其中一半的点着色,等待键盘上的下一次击键.
兼容性:在环境下测试使用win.graph或X11.适用于带有Revolution R v6.1的Windows 7 x64.在RStudio下不起作用(因为它不使用win.graph).

Gre*_*now 17
这是一个小功能(使用tcltk包),它会打开一个小窗口,等到你点击继续按钮或按任意键(当小窗口仍有焦点时),然后它会让你的脚本继续.
library(tcltk)
mywait <- function() {
tt <- tktoplevel()
tkpack( tkbutton(tt, text='Continue', command=function()tkdestroy(tt)),
side='bottom')
tkbind(tt,'<Key>', function()tkdestroy(tt) )
tkwait.window(tt)
}
Run Code Online (Sandbox Code Playgroud)
只需将mywait()脚本放在您希望脚本暂停的任何位置即可.
这适用于任何支持tcltk的平台(我认为都是常见的),会响应任何按键(不仅仅是输入),甚至可以在批处理模式下运行脚本时工作(但它仍然在批处理模式下暂停) ,所以如果你不在那里继续它将永远等待).如果没有点击或按下一个键,可以添加一个计时器,使其在设定的时间后继续.
它不会返回按下哪个键(但可以修改它以执行此操作).
Sim*_*ter 12
R和Rscript都发送''到readline并以非交互模式扫描(参见参考资料? readline).解决方案是强制stdin使用扫描.
cat('Solution to everything? > ')
b <- scan("stdin", character(), n=1)
Run Code Online (Sandbox Code Playgroud)
例:
$ Rscript t.R
Solution to everything? > 42
Read 1 item
Run Code Online (Sandbox Code Playgroud)