[R] Loop function/comparison operator problem

Duncan Murdoch murdoch at stats.uwo.ca
Tue Oct 6 01:56:28 CEST 2009


On 05/10/2009 7:47 PM, jimdare wrote:
> Hi There,
> 
> I have created the following function
> 
> format<- function(){
> repeat {
> form<-readline(paste("\nIn what format do you want to save these
> plots?\nChoose from: wmf, emf, png, jpg, jpeg, bmp, tif, tiff, ps, eps, or
> pdf.\nNote: eps is the suggested format for publication quality plots.\nPlot
> format --> "));
> 	cat("\nI'm sorry, I don't know what that format is.\nPlease try
> again\nPress ENTER...");readline()}
> 	if (form == c("wmf", "emf", "png", "jpg", "jpeg", "bmp", "tif", "tiff",
> "ps", "eps", "pdf")) {break}
> }
> 
> How do I get the program to recognise that the user has entered one of the
> formats in the last line?  Even entering "png" insted of png at the prompt
> doesn't seem to work.  Will the loop only break if I enter all of the
> possible formats?

To debug stuff like this, assign a value to form, then evaluate the 
condition.  For example,

 > form <- "png"
 > form == c("wmf", "emf", "png", "jpg", "jpeg", "bmp", "tif", "tiff",
+  "ps", "eps", "pdf")
  [1] FALSE FALSE  TRUE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE

So you could put any() around the test, or use the %in% operator instead 
of ==, or use the menu() or select.list() functions.

Duncan Murdoch




More information about the R-help mailing list