R:在等待用户输入时运行计算

时间:2016-06-06 11:46:52

标签: r multithreading input

您是否看到在等待用户输入时在R中运行计算的方法?

我正在编写一个脚本,该脚本生成由用户输入定义的不同类型的图,但是必须加载和处理第一批数据。但实际上,用户可以在处理运行时开始定​​义他想要的东西 - 这就是我想做的事情!

我认为软件包Rdsn可能提供我需要的功能,但我无法弄清楚如何。

谢谢!

1 个答案:

答案 0 :(得分:0)

你没有给我很多背景信息,也没有给出可重复的代码,所以我只提供一个简单的例子。我不熟悉Rdsn软件包,因此我将使用提供的解决方案。

# create a function to prompt the user for some input
readstuff = function(){
  stuff = readline(prompt = "Enter some stuff: ")
  # Here is where you set the condition for the parameter
  # Let's say you want it to be an integer
  stuff = as.integer(stuff)
  if(is.na(stuff)){
    return(readstuff())
  } else {
    return(stuff)
  }
}

parameter = readstuff()

print(parameter)
print(parameter + 10)

这里的关键是"来源"脚本而不是"运行"它。你可以找到"来源" RStudio右上角的按钮。您也可以使用source(yourscript)来获取它。

因此,对于要提示用户输入的每个参数,只需调用readstuff()即可。您也可以稍微调整它以使其更通用。例如:

# create a function to prompt the user for some input
readstuff = function(promptMessage = "stuff", class = "integer"){
  stuff = readline(prompt = paste("Enter the", promptMessage, ": "))
  # Here is where you set the condition for the parameter
  # Let's say you want it to be an integer
  stuff = as(stuff, class)
  if(is.na(stuff)){
    return(readstuff(promptMessage, class))
  } else {
    return(stuff)
  }
}

plotColor = readstuff("plot color", "character")
size = readstuff("size parameter")
xvarName = readstuff("x axis name", "character")

df = data.frame(x = 1:100, y = 1:100)

library(ggplot2)
p = ggplot(df, aes(x = x, y = y, size = size, color = plotColor)) + 
  labs(x = xvarName) + geom_point()
print(p)

如果类是字符,if(is.na(stuff))语句不会起作用,但我不知道如何解决这个问题,因为这个问题主要是关于如何等待用户输入。如果用户输入了除预期之外的其他内容,还有一些方法可以抑制警告消息,但是,这里还有一些主题可以在这里讨论。

您需要注意的一件重要事情是,您希望R打印或绘图的任何内容,您需要使用print()函数进行包装。否则,采购它不会打印或绘制任何东西。此外,在输入要作为字符串或字符的参数时,请勿添加引号。例如,对于plotColor,键入红色而不是"红色"在提示符中。

大多数readline代码都是从here引用的: