[R] Help with IF operator

Petr Savicky savicky at praha1.ff.cuni.cz
Fri Jan 7 09:37:11 CET 2011


On Thu, Jan 06, 2011 at 12:21:33PM -0800, ADias wrote:
> 
> Hi,
> 
> I am with a problem on how to do a comparison of values. My script is as
> follows:
> 
> repeat{
> cat("How many teams to use? (to end write 0) ")
> nro<-scan(n=1)
> if(nro==0)break
> cat("write the", nro, "teams names \n")
> teams<-readLines(n=nro)
> if (teams[1]==teams[2)next 
> else print(teams)
> }
> 
> On this example I only compare teams 1 name with teams 2 name, and if they
> are the same the scrip starts again. If I had 10 teams how could I make it
> compare the "nro" number of teams names in order to check if the same name
> has been written more then once? The idea is, if the same name is written
> more then once it should give an error and start the scrip again by asking
> the teams names again.
> 
> Two more things: With the next function the script stats from top, I mean
> starts by asking the number of teams to use. Can I make it that it goes
> directly to asking teams names?

Consider also using readline(), which reads a single line, and
%in% operator to compare the new name to the previous ones
immediately. 

  nro <- as.numeric(readline("no of teams "))
  teams <- rep(NA, times=nro)
  for (i in seq(length=nro)) {
      repeat {
          current <- readline(paste("team", i, ""))
          if (current %in% teams) {
              cat("error - repeated name\n")
          } else {
              break
          }
      }
      teams[i] <- current
  }

Petr Savicky.



More information about the R-help mailing list