如何在R中等待按键?

时间:2021-12-16 00:09:24

I want to pause my R script until the user presses a key.

我想暂停我的R脚本,直到用户按下一个键。

How do I do this?

我该怎么做呢?

4 个解决方案

#1


67  

As someone already wrote in a comment, you don't have to use the cat before readline(). Simply write:

正如已经有人在评论中写的那样,在readline()之前,你不必使用猫。简单地写:

readline(prompt="Press [enter] to continue")

If you don't want to assign it to a variable and don't want a return printed in the console, wrap the readline() in an invisible():

如果您不想将其分配给一个变量,并且不想在控制台中打印返回,请将readline()包装在一个不可见的()中:

invisible(readline(prompt="Press [enter] to continue"))

#2


69  

Method 1

方法1

Waits until you press [enter] in the console:

等待,直到您按[进入]控制台:

cat ("Press [enter] to continue")
line <- readline()

Wrapping into a function:

包装成一个函数:

readkey <- function()
{
    cat ("Press [enter] to continue")
    line <- readline()
}

This function is the best equivalent of Console.ReadKey() in C#.

这个函数在c#中是最好的等效值。

Method 2

方法2

Pause until you type the [enter] keystroke on the keyboard. The disadvantage of this method is that if you type something that is not a number, it will display an error.

暂停,直到你在键盘上键入[输入]键。这种方法的缺点是,如果您输入的东西不是一个数字,它将显示一个错误。

print ("Press [enter] to continue")
number <- scan(n=1)

Wrapping into a function:

包装成一个函数:

readkey <- function()
{
    cat("[press [enter] to continue]")
    number <- scan(n=1)
}

Method 3

方法3

Imagine you want to wait for a keypress before plotting another point on a graph. In this case, we can use getGraphicsEvent() to wait for a keypress within a graph.

假设您想要等待一个按键,然后再在图上绘制另一个点。在这种情况下,我们可以使用getGraphicsEvent()在一个图中等待一个按键。

This sample program illustrates the concept:

这个示例程序演示了这个概念:

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

Here you can see the graph, with half of its points colored, waiting for the next keystroke on the keyboard.

在这里你可以看到这个图形,它的一半颜色都是彩色的,等待键盘上的下一个按键。

Compatibility: Tested under environments use either win.graph or X11. Works with Windows 7 x64 with Revolution R v6.1. Does not work under RStudio (as it doesn't use win.graph).

兼容性:在环境下的测试中使用双赢。图或X11。与Windows 7 x64一起使用革命R v6.1。不能在RStudio下工作(因为它不使用win.graph)。

如何在R中等待按键?

#3


17  

Here is a little function (using the tcltk package) that will open a small window and wait until you either click on the continue button or press any key (while the small window still has the focus), then it will let your script continue.

这里有一个小函数(使用tcltk包),它将打开一个小窗口,等待您单击continue按钮或按任意键(尽管小窗口仍然有焦点),然后它将让您的脚本继续。

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

Just put mywait() in your script anywhere that you want the script to pause.

只需将mywait()放在您的脚本中,您希望脚本暂停。

This works on any platform that supports tcltk (which I think is all the common ones), will respond to any key press (not just enter), and even works when the script is run in batch mode (but it still pauses in batch mode, so if you are not there to continue it it will wait forever). A timer could be added to make it continue after a set amount of time if not clicked or has a key pressed.

这适用于任何平台,支持tcltk(我认为这是所有常见的),将如何应对任何按键(不仅仅是进入),甚至是在批处理模式下运行脚本时(但它仍然暂停在批处理模式中,所以如果你不继续它将永远等待)。可以添加一个定时器,使它在设定的时间后继续,如果没有单击或有一个键被按下。

It does not return which key was pressed (but could be modified to do so).

它不返回按下的键(但可以修改为这样做)。

#4


11  

R and Rscript both send '' to readline and scan in non-interactive mode (see ? readline). The solution is to force stdin using scan.

R和Rscript都发送“以非交互模式进行读取和扫描(见?)readline)。解决方法是使用扫描强制stdin。

cat('Solution to everything? > ')
b <- scan("stdin", character(), n=1)

Example:

例子:

$ Rscript t.R 
Solution to everything? > 42
Read 1 item

#1


67  

As someone already wrote in a comment, you don't have to use the cat before readline(). Simply write:

正如已经有人在评论中写的那样,在readline()之前,你不必使用猫。简单地写:

readline(prompt="Press [enter] to continue")

If you don't want to assign it to a variable and don't want a return printed in the console, wrap the readline() in an invisible():

如果您不想将其分配给一个变量,并且不想在控制台中打印返回,请将readline()包装在一个不可见的()中:

invisible(readline(prompt="Press [enter] to continue"))

#2


69  

Method 1

方法1

Waits until you press [enter] in the console:

等待,直到您按[进入]控制台:

cat ("Press [enter] to continue")
line <- readline()

Wrapping into a function:

包装成一个函数:

readkey <- function()
{
    cat ("Press [enter] to continue")
    line <- readline()
}

This function is the best equivalent of Console.ReadKey() in C#.

这个函数在c#中是最好的等效值。

Method 2

方法2

Pause until you type the [enter] keystroke on the keyboard. The disadvantage of this method is that if you type something that is not a number, it will display an error.

暂停,直到你在键盘上键入[输入]键。这种方法的缺点是,如果您输入的东西不是一个数字,它将显示一个错误。

print ("Press [enter] to continue")
number <- scan(n=1)

Wrapping into a function:

包装成一个函数:

readkey <- function()
{
    cat("[press [enter] to continue]")
    number <- scan(n=1)
}

Method 3

方法3

Imagine you want to wait for a keypress before plotting another point on a graph. In this case, we can use getGraphicsEvent() to wait for a keypress within a graph.

假设您想要等待一个按键,然后再在图上绘制另一个点。在这种情况下,我们可以使用getGraphicsEvent()在一个图中等待一个按键。

This sample program illustrates the concept:

这个示例程序演示了这个概念:

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

Here you can see the graph, with half of its points colored, waiting for the next keystroke on the keyboard.

在这里你可以看到这个图形,它的一半颜色都是彩色的,等待键盘上的下一个按键。

Compatibility: Tested under environments use either win.graph or X11. Works with Windows 7 x64 with Revolution R v6.1. Does not work under RStudio (as it doesn't use win.graph).

兼容性:在环境下的测试中使用双赢。图或X11。与Windows 7 x64一起使用革命R v6.1。不能在RStudio下工作(因为它不使用win.graph)。

如何在R中等待按键?

#3


17  

Here is a little function (using the tcltk package) that will open a small window and wait until you either click on the continue button or press any key (while the small window still has the focus), then it will let your script continue.

这里有一个小函数(使用tcltk包),它将打开一个小窗口,等待您单击continue按钮或按任意键(尽管小窗口仍然有焦点),然后它将让您的脚本继续。

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

Just put mywait() in your script anywhere that you want the script to pause.

只需将mywait()放在您的脚本中,您希望脚本暂停。

This works on any platform that supports tcltk (which I think is all the common ones), will respond to any key press (not just enter), and even works when the script is run in batch mode (but it still pauses in batch mode, so if you are not there to continue it it will wait forever). A timer could be added to make it continue after a set amount of time if not clicked or has a key pressed.

这适用于任何平台,支持tcltk(我认为这是所有常见的),将如何应对任何按键(不仅仅是进入),甚至是在批处理模式下运行脚本时(但它仍然暂停在批处理模式中,所以如果你不继续它将永远等待)。可以添加一个定时器,使它在设定的时间后继续,如果没有单击或有一个键被按下。

It does not return which key was pressed (but could be modified to do so).

它不返回按下的键(但可以修改为这样做)。

#4


11  

R and Rscript both send '' to readline and scan in non-interactive mode (see ? readline). The solution is to force stdin using scan.

R和Rscript都发送“以非交互模式进行读取和扫描(见?)readline)。解决方法是使用扫描强制stdin。

cat('Solution to everything? > ')
b <- scan("stdin", character(), n=1)

Example:

例子:

$ Rscript t.R 
Solution to everything? > 42
Read 1 item