R 语言 - 等待用户输入 scan 或 readline

标签 r input readline

我试图让用户输入几个关键字进行查询,在我的脚本中我使用了 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/

相关文章:

java - 对于两个整数用户输入,如何检测第一个输入是否传递了字符串?

java - 如果在 Java 中到达文件末尾,如何从控制台读取输入?

node.js - 在关闭事件时从 Node.js readline 模块返回数组

node.js - 在 Node.js readline shell 中清除终端窗口

c++ - 在 Rcpp 中有效地生成随机比特流

javascript - 如何允许输入的数字类型有空格和逗号

css - 增加 Shiny 应用程序中操作按钮的长度

c++ - Qt - QTextStream - 如何将光标位置设置为一行的开头?

r - R 中是否有任何 HTTP 库?

sql - R 和 SQL : Importing date and time from SQL to R