Mic*_*oda 6 multithreading r input
你有没有看到在等待用户输入时在R中运行计算的方法?
我正在编写一个脚本,用于创建由用户输入定义的不同类型的图,但是必须加载和处理第一批数据.但实际上,用户可以在处理运行时开始定义他想要的东西 - 这就是我想要做的!
我认为软件包Rdsn可能提供我需要的功能,但我无法弄清楚如何.
谢谢!
您没有给我太多上下文,也没有提供可重现的代码,所以我将仅提供一个简单的示例。我对 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)
Run Code Online (Sandbox Code Playgroud)
这里的关键是“获取”脚本而不是“运行”它。您可以在 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)
Run Code Online (Sandbox Code Playgroud)
如果类是字符,这些if(is.na(stuff))语句将不起作用,但我不会详细介绍如何解决该问题,因为这个问题主要是关于如何等待用户输入。如果用户输入的内容与预期内容不同,还有一些方法可以抑制警告消息,但同样,在这里谈论它有点偏离主题。
您必须注意的一件重要事情是,您想要 R 打印或绘制的任何内容,都需要用函数包装它print()。否则,采购它不会打印或绘制任何内容。另外,在输入字符串或字符的参数时,请勿添加引号。例如,对于plotColor,在提示中键入red 而不是“red”。
大部分readline代码都是从这里引用的: