是否可以在不要求用户按enter键的情况下使用R函数readline?
我正在编写一个需要用户输入的小函数,我已经编写了使用是否可以在不要求用户按enter键的情况下使用R函数readline?,r,user-input,R,User Input,我正在编写一个需要用户输入的小函数,我已经编写了使用readline函数的代码,但希望用户在响应控制台中的提示后不必按[enter] 我已经搜索了这么多,但没有找到解决方案,readline文档没有提供任何潜在的解决方案 timer <- function() { require(tictoc) #load required package experiment_no <- readline("Experiment number: ") while(T){ #open
readline
函数的代码,但希望用户在响应控制台中的提示后不必按[enter]
我已经搜索了这么多,但没有找到解决方案,readline
文档没有提供任何潜在的解决方案
timer <- function() {
require(tictoc) #load required package
experiment_no <- readline("Experiment number: ")
while(T){ #open infinite while loop
tic() #start timer
input_state=readline("State input: ") #allow for entry of state
if(input_state %in% 1:5){ #check if it's acceptable
elapsed=toc() #if it is then end timer and record data
write.table(cbind(experiment_no,input_state,elapsed$toc-elapsed$tic),'results.txt',col.names=F,row.names=F,quote=F,append=T)
}else if(input_state=='t'){ #if input is 't'
break #break out of while loop
}else if(input_state <1 | input_state > 5 & input_state!='t'){#if input is not and accepted state AND is not 't'
print('thats not an allowed state- please try another')
}
}
}
timer编辑:首先,这也不适用于RStudio。由于我确信RStudio确实在拦截和控制大量R,而C_菜单
可能有其他控制方法(例如,选项
),我认为RStudio更有可能是在拦截按键(从而迫使
-使用)。因此,我建议使用RStudio实现bug/feature请求
如果查看utils::menu
的源代码,您将在最后看到它的功能:
重复{
ind与“response”不同,此解决方案仅在RStudio中工作。它依赖于包捕获控制台中当前输入的能力
dynamic_readline <- function() {
while (rstudioapi::isAvailable()) {
input <- rstudioapi::getConsoleEditorContext()$contents
if (input != "") {
rstudioapi::sendToConsole("", execute = FALSE)
return(input)
}
Sys.sleep(0.1)
}
readline()
}
dynamic\u readline作为一个容易打字的人,我讨厌这样做……试着抓取输入并将其设置为某个TRUE
值,然后强制打印。无法测试。我认为你不能严格在控制台上做这件事(我也看过)。但是,如果你不介意使用图形设备,你可以做plot之类的事情(NA);getGraphicsEvent(onKeybd=identity)
,当图形窗口聚焦时,它将返回一个字母的按键。我承认这并不理想。(我没有在RStudio IDE中测试过这一点,在RStudio服务器这样的远程环境中肯定不会工作。)@Roland这是“触摸式培训”和“詹姆斯·邦德电影《永不再说永不》中的导弹指挥游戏”@Roland,我同意这可能对每个人都不理想,但这是一个个人软件包,可以简化我的工作,所以我愿意接受打字错误哈哈!