Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in R Programming by (5.3k points)
edited by

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 a question about R!

1 Answer

0 votes
by
edited by

To create a prompt/answer system to input data into R, you can use the readlines() function as follows:

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

}

fun()

Output:

What is the value of x?2

What is the value of y?4

What are the T values?1,2,3,4

What are the V values?9,8,7,6

[[1]]

[1] 6

[[2]]

[1] 10 10 10 10

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...