Re: [R] Readline - wait for user input

From: Peter Dalgaard <P.Dalgaard_at_biostat.ku.dk>
Date: Wed, 23 May 2007 16:36:00 +0200

Forest Floor wrote:
> Hi,
>
> I've seen various posts on this question, but still can't get the code
> right.
>
> If I run the following code one line at a time, it works fine. If I run
> it together as a block, however, it doesn't wait for the input and gives
> an error.
>
> There must be a way to have are pause/wait for an answer, but I can't
> seem to find it. Thanks! J
>
> Code:
>
> choosefunction <- function(){readline("1. linear, 2. linear with lag, 3.
> nonlinear ")}
> ans <- as.integer(choosefunction())
> if (ans==1){K2=x1}
> if (ans==2){K2=x2 }
> if (ans==3){K2=x3 }
> ans
>
> Error text:
> > ans <- as.integer(choosefunction())
> 1. linear, 2. linear with lag, 3. nonlinear if (ans==1) {K2=x1}]}
> Warning message:
> NAs introduced by coercion
> > if (ans==2){K2=x2) }
> Error in if (ans == 2) { : missing value where TRUE/FALSE needed
> > if (ans==3){K2=x3}
> Error in if (ans == 3) { : missing value where TRUE/FALSE needed
> > ans
> [1] NA
>

As you may have realized already, the issue is that choosefunction() takes the next command as its input. Since "if (ans==1){K2=x1}" isn't an integer "ans" becomes NA, and it just goes downhill from there.

An extra set of braces may help

> choosefunction <- function(){readline("1. linear, 2. linear with lag, 3.
+ nonlinear ")}
> {ans <- as.integer(choosefunction())

+ if (ans==1){K2=x1}
+ if (ans==2){K2=x2 }
+ if (ans==3){K2=x3 }
+ ans}

1. linear, 2. linear with lag, 3.
nonlinear 3
Error: object "x3" not found

It still doesn't quite work, but the reason(s) for that should be plain to see.

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

______________________________________________
R-help_at_stat.math.ethz.ch mailing list
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.
Received on Wed 23 May 2007 - 14:45:07 GMT

Archive maintained by Robert King, hosted by the discipline of statistics at the University of Newcastle, Australia.
Archive generated by hypermail 2.2.0, at Mon 18 Jun 2007 - 10:32:01 GMT.

Mailing list information is available at https://stat.ethz.ch/mailman/listinfo/r-help. Please read the posting guide before posting to the list.