R: Performing calculations while waiting for user input

Do you see a way to start the calculation in R, waiting for user input?

I am writing a script that makes different types of graphs that are user defined, but in the first batch of data you need to load and process it. But in fact, the user can begin to determine what he wants already during processing - this is what I would like to do!

I think the Rdsn package can provide the features I need, but I could not figure out how to do this.

Thanks!

+6
source share
1 answer

You did not give me much context or reproducible code, so I will just give a simple example. I am not familiar with the Rdsn package, so I will use the provided solution that I know.

# 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 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) 

The key here is the "source" script instead of the "run". You can find the "source" button in the upper right corner of RStudio. You can also use source(yourscript) for its source.

So, for each parameter that you want to ask the user for input, just call readstuff() . You can also tweak it a bit to make it more general. For instance:

 # 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 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) 

The if(is.na(stuff)) will not work if the class is a character, but I will not go into details on how to fix this, since this question mainly concerns how to wait for user input. There are also ways to suppress warning messages if the user entered something other than what was intended, but again, a little off topic to talk about it here.

One important thing you should pay attention to is that you want R to print or draw, you need to wrap it with the print() function. Otherwise, the search will not print and do nothing. Also, when entering a parameter that is intended for a string or character, do not add quotation marks. For example, for plotColor, enter red instead of β€œred” in the tooltip.

In most cases, the readline code refers to here :

0
source

All Articles