if i understand correctly, you want to specify how often to repeat execution of a function interactively, not programmatically. You can do this with readline
:
I need a function which gives me some option to choose the number of repetitions
# some function
funcA <- function(){
cat("i am funcA\n")
}
# some function that interactively repeats funcA a specified amount of times
doNTimesA <- function() {
Ntimes <- readline("number of repeats: ")
for (i in 1:Ntimes) funcA()
}
doNTimesA()
I mean, a function which asks me whether I want to continue or not
funcB <- function(){
while (TRUE) {
cat("i am funcB\n")
continue <- readline("again? y/n: ")
if (tolower(continue)=="n") break
}
cat("funcB is done")
}
funcB()
edit: for your specific case, you can wrap your function declaration in a while
loop that asks you whether you want to continue, as in my example funcB
above. updated where it also stores its output:
func <- function(){
#initiate an iteration counter and an outputlist
counter <- 1
output <- list()
#start an infinite loop
while (TRUE) {
#do your thing
id.co1 <- identify(f$speed, f$dist,labels=row.names(f), n = 2, pos = TRUE,plot = TRUE)
xy <- f[c(id.co1$ind[1],id.co1$ind[2]),]
lines(xy, col="red", lwd=5)
lm(dist~speed, xy)
abline(coef(lm(dist~speed, xy)),col="blue")
x.co1 <- f$speed[id.co1$ind[1]:id.co1$ind[2]]
y.co1 <- f$dist[id.co1$ind[1]:id.co1$ind[2]]
m.co1 <- lm(y.co1 ~ x.co1)
#store the result at counter index in the outputlist
output[[counter]] <- list(xco =x.co1, yco=y.co1, lm =m.co1)
counter <- counter+1
#prompt for next iteration
continue <- readline("again? y/n: ")
#break the loop if the answer is 'n' or 'N'
if (tolower(continue)=="n") break
}
#return your output
output
}
What happens now is that after every iteration, the function asks if you want to rerun the function: continue <- readline("again? y/n: ")
and checks whether you have answered N
or n
. You can add more checks on the answer if you like; if you answer anything but N
or n
now, the loop will run again.
If you run all <- func()
, after you're done you can access each iterations' result using all[[1]]
, all[[2]]
, etc.
Please note that it's generally frowned upon to manipulate objects outside your function environment, so it would be cleaner to pull the initial plot generation into your function.