readline() does not wait for user's input


TS Contributor
Hi All,
I am trying to write down a script to simplify my work in making probability density charts for (prehistoric) calendar dates.
I wish to acknowledge the help received by Vinux in solving some issues deriving from my ggplot2 limited skill (this is the earlier thread).

The issue I am experiencing is that the command readline() does not wait for user to enter some values.

What puzzles me is that the piece of code that is not working is:
answer <- readline(prompt="Do you want to set different limits for the x axis (y/n)? ")
R does not wait for user's input, and skip directly to the next section.

I have tried to figure out where the issue is, trying to manually enter the code line by line, trying to test for possible conflict with ggplot2 or xlsx packages, etc etc. But I did not manage to spot the problem.

Another thing that puzzles me is that I used readline() previously in other scripts, and it worked as expected. So, I am wondering what is going wrong with this particular code. I bet it is something stupid, but I am not managing to spot it.

Any hint is welcome.


dataset attached


mydata <- read.xlsx(file.choose(), sheetIndex=1, header=TRUE)

plot.a <- ggplot(data=mydata)+ geom_line(aes(x=dates,y=prob,color=site))
plot.b <- ggplot(data=mydata)+geom_area(position="identity", aes(x=dates,y=prob,fill=site), alpha=0.5)
plot.c <- plot.a+geom_area(position="identity",aes(x=dates,y=prob,fill=site), alpha=0.5)


answer <- readline(prompt="Do you want to set different limits for the x axis (y/n)? ")

if (answer == "n") { 
    print("script ends: enjoy your plots")
} else { 
	c <- as.numeric(readline(prompt="Lower (i.e., left) limit? "))
	d <- as.numeric(readline(prompt="Upper (i.e., right) limit? "))
	plot.a.resized <- ggplot(data=mydata)+ geom_line(aes(x=dates,y=prob,color=site)) + scale_x_continuous  (limits =c(c,d))
    plot.b.resized <-ggplot(data=mydata)+geom_area(position="identity", aes(x=dates,y=prob,fill=site), alpha=0.5) + scale_x_continuous(limits =c(c,d))
    plot.c.resized <- plot.a.resized+geom_area(position="identity",aes(x=dates,y=prob,fill=site), alpha=0.5)



Phineas Packard
I came across this the other day. If I understand correctly, it will work if you run line-by-line (where interactive() == TRUE) but not if you run the script as a whole where (where interactive() == FASLE). Thus you could add:

       answer<- y, 
       answer <- readline(prompt="Do you want to set different limits for the x axis (y/n)? ")
Which will wait for user response if run line by line or will default to a given value otherwise. Not ideal but you could try tcltk as suggested in the link


Ambassador to the humans
Alternatively you can get readLines to get input from you even if it's not an interactive session
cat("What is your name?\n")
inp <- readLines(file("stdin"), n = 1L)
cat(paste("Hello", inp, "\n"))