等待用户输入5秒钟,否则使用默认值

Jul*_*ier 5 user-input r wait

我想给用户一个输入输入的机会,如果他们在5秒后没有输入任何内容,则使用默认值.

这是输入部分:

input <- readline(prompt="Do something? (y/n): ")
Run Code Online (Sandbox Code Playgroud)

有没有办法在R中做到这一点?

man*_*ark 2

以下是我如何完成窗口提示,允许用户选择要在集群中启动的线程数。它使用默认值,然后在按下“确定”按钮或 5 秒后继续。

library(tcltk2)

clusterCount = 1

tklist <- list()
tklist <- within(tklist, {
  # define processor input window
  win1 <- tktoplevel()
  rb1 <- tk2radiobutton(win1)
  rb2 <- tk2radiobutton(win1)
  rb3 <- tk2radiobutton(win1)
  rb4 <- tk2radiobutton(win1)
  rbCluster <- tclVar(clusterCount)
  tkconfigure(rb1, text = "one",  variable = rbCluster, value = 1L)
  tkconfigure(rb2, text = "two",  variable = rbCluster, value = 2L)
  tkconfigure(rb3, text = "three", variable = rbCluster, value = 3L)
  tkconfigure(rb4, text = "four", variable = rbCluster, value = 4L)
  onOK <- function() {
    clusterCount <<- as.integer(tclvalue(rbCluster))
    tkdestroy(win1)
  }
  butOK <- tk2button(win1, text = "OK", width = -8, command = onOK)

  # geometry manager
  tkgrid(tk2label(win1, text = "how many cores?"), padx = 10, pady = c(15, 5))
  tkgrid(rb1, padx = 10, pady = c(0, 5))
  tkgrid(rb2, padx = 10, pady = c(0, 15))
  tkgrid(rb3, padx = 10, pady = c(0, 15))
  tkgrid(rb4, padx = 10, pady = c(0, 15))
  tkgrid(butOK, padx = 10, pady = c(5, 15))
  tclAfter(5000, function() tkdestroy(win1)) # delay for prompt and then close window to proceed
  tkfocus(win1)
  tkwait.window(win1)
})
Run Code Online (Sandbox Code Playgroud)

窗口关闭后,clusterCount将保留默认值 1,也可更改为 2、3 或 4。