创建一个提示/回答系统,将数据输入 R

我已经创建了一些 R 代码,供那些对 R 一无所知的人使用(尽管我自己也很嫩)。我一直让人们将初始数据粘贴到 R 控制台(结果有好有坏) ,我希望为人们输入数据设置一种更加用户友好的方式。

理想情况下,某人可以坐在控制台前,键入一条命令,并被提示如何输入数据的具体问题。

例如,一个人加载 r 并看到一个提示:

What is x value?

用户输入:

2

下一个提示:

What is y value?

输入人员:

3

下一个提示:

 What are T values?

输入人员:

 4,3,2,1

下一个提示:

V 值是什么?

输入人员:

4,5,6,9

使用这4个新定义的变量(X,Y,T,V) R 的下一步是运行预先编写的代码

X+Y
V+T

在控制台中,答案会弹出来

5
8 8 8 10

大家都很开心

我很抱歉,因为这不是一个可重复的代码类型的问题,但我不知道如何处理使 R 问问题,而不是我问问题关于 R!

102430 次浏览

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


}

Since this question was brought back from the dead, it's probably writing an updated answer.

If a GUI is at all helpful in this case, the Shiny package is now well-integrated with RStudio, and it would be very easy to implement this as a Shiny application. The website http://shiny.rstudio.com has more info, including examples and documentation.

It may be overkill for this particular case, but the swirl package is good for interactively introducing R to beginners.

swirl is a software package for the R programming language that turns the R console into an interactive learning environment. Users receive immediate feedback as they are guided through self-paced lessons in data science and R programming.

The instructions for generating content can be found here: http://swirlstats.com/instructors.html.

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:

Here is an example if you want to use menu it inside another function!

fun<-function(){
input<-NULL
x<-NULL
input<-menu(c("lowercase", "UPPERCASE"),title="What type of letters do want to assign to x?") + 1
if (input == 1){
x<-NULL
message('Nothing assigned to x')
}
if (input == 2){
x<-letters
message('x is lowercase!')
}
if (input == 3){
x<-letters
message("x is UPPERCASE!")
}
}