Question

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=\",\")"

Meanwhile when I use the source() command, I have my user input respected.

So is there any way to be able to input some things while executing the code right from the R software?

Was it helpful?

Solution

This is how I use readLInes:

FUN <- function(x) {

    if (missing(x)) {
        message("Uhh you forgot to eneter x...\nPlease enter it now.")
        x <- readLines(n = 1)
    }
    x
}

FUN()

Or maybe something along these lines:

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

EDIT: 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"
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top