[R] Getting scan() -command to work during the program run
dwinsemius at comcast.net
Tue Dec 20 18:55:51 CET 2016
> On Dec 20, 2016, at 12:37 AM, Atte Tenkanen <attenka at utu.fi> wrote:
> How to get scan(file="") command to ask my input from the keyboard?
> If I put the command straight to the console it works
> > X1 <- scan(n=1)
> 1: 22
> Read 1 item
> but as a part of a program it just continues without asking my value?
> > X1 <- scan(n=1)
As "part of a program" there is no console input file when run in non-interactive mode. Efforts to make a non-interactive session into an interactive session are well documented in the rhelp archives. Search:
If you did that inside a function which you ran inside an interactive session and did not return the value there would of course be no value, but that would not give you response you report. You would be expected to use the 'file'-parameter for specifying the source of input when using scan in a script.
If my only code is a single line in a text file named 'Untitled.R':
X1 <- scan(n=1)
Running just that with Rscript at the system console does give me:
Read 0 items
Now make a data file named 'myfile.txt' and a source file named "Untitled.R" and use it to create a data file named myfile.txt and then read from it.
cat("5", "\n", file="myfile.txt")
X1 <- scan(file="myfile.txt")
The source Untitled.R or run with Rscript.
From a Unix shell console:
$ Rscript Untitled
#omitting the information about my R version etc, etc
Read 1 item
If I execute that with no 'myfile.txt' file in my working directory it throws an error and I get "Error in file(file, "r") : cannot open the connection"
If I run this script file:
X1 <- scan()
I do not get an error from a missing file argument to `scan` but X1 does not get set to a value but I do get:
Error in scan() : scan() expected 'a real', got 'X1'
> Read 0 items
> Atte Tenkanen
> R-help at r-project.org mailing list -- To UNSUBSCRIBE and more, see
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
Alameda, CA, USA
More information about the R-help