Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating a Prompt/Answer system to input data into R

Tags:

r

I've created some R code for use by people who know nothing of R (though I'm pretty green myself). I've been having people paste in the initial data to the R console (with mixed results), and I was hoping to set up a more user friendly way for people to enter in data.

Ideally someone could sit down at the console, type in a command, and be prompted with specific questions on how to enter the data.

For example, a person loads up r and sees a prompt:

What is x value? 

The person types in:

2 

Next prompt:

What is y value? 

Person types in:

3 

Next prompt:

 What are T values? 

Person types in:

 4,3,2,1 

Next prompt:

What are V values?

Person types in :

4,5,6,9 

And with these 4 newly defined variables (X,Y,T,V) R's next step is to run the pre-written code

X+Y V+T 

And in the console the answers pop up

5 8 8 8 10 

And everyone is happy

My apologies as this is not a reproducible code kind of question, but I'm not sure how to approach making R ask questions as opposed to me asking question about R!

like image 479
Vinterwoo Avatar asked Jun 13 '12 01:06

Vinterwoo


People also ask

How do you ask for input in R?

One can also show message in the console window to tell the user, what to input in the program. To do this one must use a argument named prompt inside the readline() function.

What is R prompt function?

The prompt function creates a package help file for object. This function should be used to generate help files for new objects or functions being added to an R package. object – An R object, most often a function or a data frame.

How do you wait for user input in R?

Just put mywait() in your script anywhere that you want the script to pause.


2 Answers

Since this is supposed to be used as interactive code only, readline() can work for you. I did not add any error checking, but you'd probably want to do a fair amount of that to ensure proper input. Here's the core concept though:

fun <- function(){   x <- readline("What is the value of x?")     y <- readline("What is the value of y?")   t <- readline("What are the T values?")   v <- readline("What are the V values?")    x <- as.numeric(unlist(strsplit(x, ",")))   y <- as.numeric(unlist(strsplit(y, ",")))   t <- as.numeric(unlist(strsplit(t, ",")))   v <- as.numeric(unlist(strsplit(v, ",")))    out1 <- x + y   out2 <- t + v    return(list(out1, out2))  } 
like image 114
Chase Avatar answered Sep 20 '22 19:09

Chase


See also ?menu from utils for a simple text base menu interface and prompt, which is also used in devtools.

Here is an example:

> menu(c("Yes", "No"), title="Do you want this?") Do you want this?   1: Yes 2: No  Selection: 
like image 45
patr1ckm Avatar answered Sep 17 '22 19:09

patr1ckm