[R] simple if statement

Philipp Pagel philipp.pagel.lists at t-online.de
Fri Apr 7 09:55:47 CEST 2006

On Fri, Apr 07, 2006 at 02:58:00AM -0400, Brian Quinif wrote:
> 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

What you are looking for is not an if clause but logical indexing:

years[years=="Freshmen"] <- 1
years[years=="Sophomores"] <- 2

Of course it's still a character vector so you will have to do

years = as.numeric(years)

Have a look at the manual (Introduciotn to R) for more details.

Another question is what you have in mind. To me it looks like what you
are trying to do is make a factor on your own. Maybe this is what you


or maybe

factor(years, levels=c("Freshmen", "Sophomores"))

if you want more control over the coding.


Dr. Philipp Pagel                            Tel.  +49-8161-71 2131
Dept. of Genome Oriented Bioinformatics      Fax.  +49-8161-71 2186
Technical University of Munich
Science Center Weihenstephan
85350 Freising, Germany


Institute for Bioinformatics / MIPS          Tel.  +49-89-3187 3675
GSF - National Research Center               Fax.  +49-89-3187 3585
      for Environment and Health
Ingolstädter Landstrasse 1
85764 Neuherberg, Germany

More information about the R-help mailing list