【问题标题】:Add 'y to confirm' confirmation dialogue to an R function? [duplicate]将“y 确认”确认对话框添加到 R 函数? [复制]
【发布时间】:2020-11-12 10:51:23
【问题描述】:

对于某些 R 函数,提示用户确认他们确定他们确实想要运行该函数可能很有用。例如,一些很少运行的函数,几乎可以肯定会以交互方式运行(即在用户在场的情况下),并且会执行不可逆的操作,例如从文件系统中清除临时文件等。

有没有办法在 R 函数中提示用户进行键盘输入,这样用户必须按“y”继续(或“n”忽略,“c”取消等)

somefunction <- function() {
  
  # -- code for prompt for user confirmation --

  # some irreversible actions 
  # e.g. file.remove(...)
}

【问题讨论】:

    标签: r


    【解决方案1】:

    为什么不使用简单的readline 函数来获取用户的输入?

    checkFunction <- function() {
      user_input <- readline("Are you sure you want to run this? (y/n)  ")
      if(user_input != 'y') stop('Exiting since you did not press y')
      print('Do something')
    }
    
    checkFunction()
    #Are you sure you want to run this? (y/n)  y
    #[1] "Do something"
    
    checkFunction()
    #Are you sure you want to run this? (y/n)  n
    #Error in checkFunction() : Exiting since you did not press y
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-01-03
      • 1970-01-01
      • 2012-09-18
      • 2011-05-24
      • 2016-02-02
      • 2023-04-03
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多