[R] simple if statement

Prof Brian Ripley ripley at stats.ox.ac.uk
Fri Apr 7 09:27:10 CEST 2006

On Fri, 7 Apr 2006, Brian Quinif wrote:

> I am ashamed to be asking this question, but I couldn't find the
> solution anywhere.  Searching for "if" and "R" is not very
> productive...
> I cannot get a simple if statement to work.
> I have data on college students.  I want to make a string variable
> that has the names of the years.  That is, when the year variable i is
> equal to 1, I want to have a variable called years equal to
> "Freshmen".
> I tried this
> years <- "Freshmen" if i==1
> years <- "Sophomores" if i==2
> and so on, but I couldn't get it to work.  How can I get this variable to work?

Most simply:

years <- c("Freshmen", "Sophomores")[i]

What you seem to be trying to do can be written

if(i == 1) years <- "Freshmen"
if(i == 2) years <- "Sophomores"

but then 'years' is undefined if !i %in% c(1,2).  Better ways to program 
that are

years <- switch(i, "Freshmen", "Sophomores")

(which gives NULL otherwise) or

years <- if(i == 1) "Freshmen" elseif(i == 2) "Sophomores" else "unknown"

of (vectorized)

years <- ifelse(i == 1, "Freshmen",
                         ifelse(i == 2, "Sophomores", "unknown"))

But the first solution is both vectorized and simple.

Brian D. Ripley,                  ripley at stats.ox.ac.uk
Professor of Applied Statistics,  http://www.stats.ox.ac.uk/~ripley/
University of Oxford,             Tel:  +44 1865 272861 (self)
1 South Parks Road,                     +44 1865 272866 (PA)
Oxford OX1 3TG, UK                Fax:  +44 1865 272595

More information about the R-help mailing list