Dear all, I am looking for some procedure to send inputs to a function
interactively. Here is an example:
fn1 <- function(x = 10) {
y <- 0
# ask user whether he wants to put some other value for "y"
# R will show 2 options: 1. y = 2
# 2. y = 3
# user will choose either options 1 or 2
# once user is done, function will over-write the existing value of y,
with say, option 2. Therefore current value of y is 2. Then R will
continue calculation
return(x*y)
}
Here obviously I can put "y" as the 2nd input of fn1(), however I want
to do so interactively.
Can friends here direct me how to do that?
Thanks,
Have you tried scan()?:> y=scan()1: 2 2: Read 1 item> y[1] 2 -- View this message in context: http://r.789695.n4.nabble.com/Supplying-function-inputs-interactively-tp2536003p2536004.html Sent from the R help mailing list archive at Nabble.com.
On Sat, Sep 11, 2010 at 7:17 PM, Christofer Bogaso <bogaso.christofer at gmail.com> wrote:> Dear all, I am looking for some procedure to send inputs to a function > interactively. Here is an example: > > fn1 <- function(x = 10) { > y <- 0 > # ask user whether he wants to put some other value for "y" > # R will show 2 options: 1. y = 2 > # ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?2. y = 3 > # user will choose either options 1 or 2 > # once user is done, function will over-write the existing value of y, > with say, option 2. Therefore current value of y is 2. Then R will > continue calculation > return(x*y) > } >Try this: ysquared <- function(y) { if (missing(y)) y <- as.numeric(readline("Enter y: ")) y*y } ysquared() -- Statistics & Software Consulting GKX Group, GKX Associates Inc. tel: 1-877-GKX-GROUP email: ggrothendieck at gmail.com
Is this what you would expect to have. Definitely you can make this function
more elegant:
fn1 <- function(x = 10) {
cat("Please type the option number to get your Y value:\n\n")
cat(" 1. Y = 1.\n
2. Y = 2.\n
3. Use the default y.\n
4. Choose my own value for y.\n\n")
opt=scan()
if (opt==3) y <-0
else if (opt==4) {
cat("Please type your Y value:\n\n")
y=scan()
}
else y = opt
return(x*y)
}
--
View this message in context:
http://r.789695.n4.nabble.com/Supplying-function-inputs-interactively-tp2536003p2536012.html
Sent from the R help mailing list archive at Nabble.com.