[R] Problem with if statement

Erik Iverson eiverson at NMDP.ORG
Wed Dec 9 01:52:22 CET 2009

You can use the "ifelse" function for vectorized conditionals like you have here. See ?ifelse. 
From: r-help-bounces at r-project.org [r-help-bounces at r-project.org] On Behalf Of Arthur Burke [Art.Burke at educationnorthwest.org]
Sent: Tuesday, December 08, 2009 6:45 PM
To: r-help at r-project.org
Subject: [R] Problem with if statement

I am trying to use the value of an ID variable in an if statement and
not getting the results I expected.

# ID values for two school districts
> with(rf, tapply(DistrictID, DistrictName, min) )

Aberdeen School Dist. # 58         Buhl Joint School District
                             59340                              53409

This creates DNAME as I expected ...

rf$DNAME[rf$DistrictID==59340] <- 'Aberdeen'
rf$DNAME[rf$DistrictID==53409] <- 'Buhl'

> with(rf, table(DistrictName, DNAME) )
DistrictName                         Aberdeen Buhl
  Aberdeen School Dist. # 58              242    0
  Buhl Joint School District                0  428

But these if statements ...

if(rf$DistrictID == 59340) {rf$D.NAME <- 'Aberdeen'}
if(rf$DistrictID == 53409) {rf$D.NAME <- 'Buhl'}

Lead to this ...

with(rf, table(DistrictName, D.NAME) )

DistrictName                         Aberdeen
  Aberdeen School Dist. # 58              242
  Buhl Joint School District              428

What am I doing wrong in the if statement?



Art Burke

Associate, Evaluation Program

Education Northwest

101 SW Main St, Ste 500

Portland, OR 97204

Phone: 503.275.9592

Art.Burke at educationnorthwest.org
<mailto:Art.Burke at educationnorthwest.org>

http://educationnorthwest.org <http://educationnorthwest.org/>

We have recently changed our name to "Education Northwest" from
"Northwest Regional Educational Laboratory." Please note the new e-mail
and Web addresses in the signature above. You may continue to find us on
the Web at http://www.nwrel.org <http://www.nwrel.org/>  for the
immediate future as well.


        [[alternative HTML version deleted]]

R-help at r-project.org mailing list
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.

More information about the R-help mailing list