[R] if() command

Huntsinger, Reid reid_huntsinger at merck.com
Tue Sep 13 17:01:03 CEST 2005

First, "==" is logical comparison, so if you want to create a variable based
on both "age" and "group" you can do that. However, it looks like you want
to define the variable "group", so you want to use "<-" or "=" for that. 

Second, if you're typing this at a command prompt, you need to make sure you
tell R you're not finished when it looks like you could be. There are
several ways to do this. One is to put everything inside braces; another is
to deliberately leave lines incomplete, like

if (age <= 10) {
   group <- 1
} else {
   if (age <= 20) {
      group <- 2
   } else group <- 3

Third, this will work for a vector of length 1. If you want to take a vector
"age" and produce a corresponding vector "group", you'll need to put this in
a loop, or use "lapply", or some iteration.

Fourth, you can also write the above as 

> group <- if (age <= 10) 1 else if (age <= 20) 2 else 3

that is, if() returns a value you can assign.

Finally, besides "ifelse" you can use "cut" for this particular task.

Reid Huntsinger

-----Original Message-----
From: r-help-bounces at stat.math.ethz.ch
[mailto:r-help-bounces at stat.math.ethz.ch] On Behalf Of Carlos Maurício
Cardeal Mendes
Sent: Tuesday, September 13, 2005 9:29 AM
To: r-help at stat.math.ethz.ch
Subject: [R] if() command

Hi everyone !

Could you please help me with this problem ?

I´ve trying to write a code that assign to a variable the content from 
another, but all I´ve got is a message error. For example:

if (age <=10) {group == 1}
else if (age > 10 & age <= 20) {group == 2}
else {group == 3}

Syntax error


if (age <=10) {group == 1}
else (age > 10 & age <= 20) {group == 2}
else {group == 3}

Syntax error

I know that is possible to find the solution by ifelse command or even 
recode command, but I´d like to use this way, because I can add another 
variable as a new condition and I believe to expand the possibilites.


R-help at stat.math.ethz.ch mailing list
PLEASE do read the posting guide!

More information about the R-help mailing list