我试图让用户输入几个关键字进行查询,在我的脚本中我使用了 scan 或 readline。我使用 R-embeeded 脚本编辑器 (Windows) 进行了尝试,但是当我执行代码时,它使用我的下一行脚本作为标准输入。 这是我的(部分)脚本
keywords <- scan(what=character(), nlines=1)
keywords <- paste(keywords, collapse=",")
keywords
这是从编辑器执行时的输出
> keywords <- scan(what=character(), nlines=1)
1: keywords <- paste(keywords, collapse=",")
Read 4 items
> keywords
[1] "keywords" "<-" "paste(keywords," "collapse=\",\")"
同时,当我使用 source() 命令时,我会尊重我的用户输入。
那么有什么方法可以在直接从 R 软件执行代码的同时输入一些东西吗?
最佳答案
这就是我使用 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 中的方法...
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 语言 - 等待用户输入 scan 或 readline,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22253899/