Skip to content

if() command

1 message · Huntsinger, Reid

#
Looping would look like:

group <- vector(length=length(age))

for (i in 1:length(age)) {
  group[i] <- if (age[i] <= 10) 1 else if (age[i] <= 20) 2 else 3
}

Another way to do this is to write a function, say "category", like

category <- function(x) if(x <= 10) 1 else if (x <= 20) 2 else 3

and then apply the function to all elements of "age" like

group <- sapply(age,category)

(This is a common way to vectorize a function.)

Reid Huntsinger

-----Original Message-----
From: Carlos Mauricio Cardeal Mendes [mailto:mcardeal at ufba.br] 
Sent: Wednesday, September 14, 2005 1:21 PM
To: Huntsinger, Reid
Cc: r-help at stat.math.ethz.ch
Subject: Re: [R] if() command


Hello reid ! About your third explanation, could you please write the 
complete code including that option: a loop ?

Forgiveme,  I'm trying to learn R and my mind is full of  other 
statistical program syntax. And I'd like very very much to improve my 
knowledge using R and maybe contribute to someone, someday, somehow.

Thanks, again

Mauricio

Huntsinger, Reid escreveu:
based
you
vector
in
---