David C. Howell wrote:> I have been having problems with using scan(). I searched the archives
> and found someone with the same problem several years ago, but did not
> find a solution.
>
> I want to prompt the user for input, scan in that input, and then go on
> to use it as a variable.
>
> The simplest version of my program is
>
> cat("enter m","\n")
> m <- scan(n = 1, quiet = T)
> m
>
> If I enter these lines one at a time, they work perfectly and I get the
> following output, which is just want I want..
> > cat("enter m","\n")
> enter m
> > m <- scan(n = 1, quiet = T)
> 1: 24
> > m
> [1] 24
> >
>
> However if I submit the three lines together, as you would when running
> a program, I get
>
> > cat("enter m","\n")
> enter m
> > m <- scan(n = 1, quiet = T)
> 1: m
> 1:
> Error in scan(file, what, nmax, sep, dec, quote, skip, nlines,
> na.strings, :
> scan() expected 'a real', got 'm'
> >
>
> In this case the program is reading the line after the scan function as
> the input to scan, rather than pausing for my entry. The help archives
> suggested putting this as a function "e.g., getn()" but that
gives the
> same result.
>
> The scan help file doesn't address this and the help archives don't
give
> me what I need. How do I cause the program to wait for keyboard entry
> from me?
It _is_ waiting for a keyboard entry. It is just that you are sending it
an "m"...
If you read both R expressions and data from the same input stream, you
have to be careful to get them in the right order. If you want to read
multiple expressions before executing any of them, you can use various
devices:
A: put them on the same line
> m <- scan() ; m
1: 1 2 3
4:
Read 3 items
[1] 1 2 3
B: use a compund expression
> {
+ m <- scan()
+ m
+ }
1: 4 5 6
4:
Read 3 items
[1] 4 5 6
C: use a function
> f <- function(){
+ m <- scan()
+ m
+ }
> f()
1: 7 8 9
4:
Read 3 items
[1] 7 8 9
D: Source code from a file
> source("foo.R")
1: 1 2 4
4: 3 7 9
7:
Read 6 items
[1] 1 2 4 3 7 9
> cat(readLines("foo.R"), sep="\n")
m <- scan()
print(m)
> I am running version 2.8 on a Windows machine, but the problem goes back
> to much earlier versions.
>
> While I'm asking, is there a way to suppress the echoing of lines? I
> would like to omit the lines above that begin with ">". I
cannot find
> "echo" using help.search and can't think of another name to
search under.
>
> Thanks,
>
> Dave Howell
>
--
O__ ---- Peter Dalgaard ?ster Farimagsgade 5, Entr.B
c/ /'_ --- Dept. of Biostatistics PO Box 2099, 1014 Cph. K
(*) \(*) -- University of Copenhagen Denmark Ph: (+45) 35327918
~~~~~~~~~~ - (p.dalgaard at biostat.ku.dk) FAX: (+45) 35327907