R语言-等待用户输入带有扫描或读取行 [英] R Language - Waiting for user input with scan or readline
问题描述
我试图让用户输入一些查询关键字,在我的脚本中,我使用了scan或readline.我使用R嵌入式脚本编辑器(Windows)进行了尝试,但是当我执行代码时,它将下一行脚本用作标准输入. 这是我的脚本(一部分)
I'm trying to get the user to input a few keywords for a query, and in my script I used either scan or readline. I tried it using the R-embeeded script editor (Windows) but when I execute the code, it uses my next lines of script as the standard input. Here is my (part of) script
keywords <- scan(what=character(), nlines=1)
keywords <- paste(keywords, collapse=",")
keywords
这是从编辑器执行时的输出
And here is the output when executed from the editor
> keywords <- scan(what=character(), nlines=1)
1: keywords <- paste(keywords, collapse=",")
Read 4 items
> keywords
[1] "keywords" "<-" "paste(keywords," "collapse=\",\")"
同时使用source()命令时,我尊重了用户输入.
Meanwhile when I use the source() command, I have my user input respected.
那么在从R软件执行代码的同时,有什么方法可以输入一些东西呢?
So is there any way to be able to input some things while executing the code right from the R software?
推荐答案
这就是我使用readLInes
的方式:
FUN <- function(x) {
if (missing(x)) {
message("Uhh you forgot to eneter x...\nPlease enter it now.")
x <- readLines(n = 1)
}
x
}
FUN()
或者也许是这些东西:
FUN2 <- function() {
message("How many fruits will you buy")
x <- readLines(n = 1)
message("Good you want to buy %s fruits.\n Enter them now.")
y <- readLines(n = x)
paste(y, collapse = ", ")
}
FUN2()
编辑:使用Rgui中的方法...
With your approach in Rgui...
FUN3 <- function(n=2) {
keywords <- scan(what=character(), nlines=n)
paste(keywords, collapse=",")
}
## > FUN3 <- function(n=2) {
## + keywords <- scan(what=character(), nlines=n)
## + paste(keywords, collapse=",")
## + }
## > FUN3()
## 1: apple
## 2: chicken
## Read 2 items
## [1] "apple,chicken"
这篇关于R语言-等待用户输入带有扫描或读取行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!