[R] ifelse() fill order and recycling rules [Sec=Unclassified]

John McKinlay John.McKinlay at aad.gov.au
Thu Aug 28 01:30:35 CEST 2008


Hi all,

Using R v2.7.1, platform i386-pc-mingw32

Can someone please shed some light on the behaviour of ifelse() for me?
My intent is to calc relative proportions of z$b, at the same time
subsetting z$b based on z$a. I could attack the problem other ways
(suggestions welcome) but I am also intrigued by the _order_ in which
ifelse seems to assign values, and how recycling works. For instance, 
	
z <- data.frame(a = c(1,2,3,4,1), b = 6:10)
z$c <- ifelse(z$a > 1, z$b[z$a > 1]/sum(z$b[z$a > 1]), NA)
z # seems to have filled z$c by row 4,2,3
  a  b         c
1 1  6        NA
2 2  7 0.3333333
3 3  8 0.3750000
4 4  9 0.2916667
5 1 10        NA

z$b[z$a > 1]/sum(z$b[z$a > 1]) # order looks fine here
[1] 0.2916667 0.3333333 0.3750000


z$d <- ifelse(z$a > 1, 6:8, NA) # fills by row 4,2,3 (as above) z$e <-
ifelse(z$a > 1, 6:7, NA) # recycling, but why values 7,6,7 instead of
6,7,6 ? 

z
  a  b         c  d  e
1 1  6        NA NA NA
2 2  7 0.3333333  7  7
3 3  8 0.3750000  8  6
4 4  9 0.2916667  6  7
5 1 10        NA NA NA

TIA for any insight into how ifelse is filling/recycling in this
instance. I know there's not much code in ifelse, but it's still not
immediately apparent to me why I'm getting what I'm seeing.

John.mckinlay at aad.gov.au

Applied Statistics
Southern Ocean Ecosystems
Australian Antarctic Division, Tasmania

___________________________________________________________________________

    Australian Antarctic Division - Commonwealth of Australia
IMPORTANT: This transmission is intended for the addressee only. If you are not the
intended recipient, you are notified that use or dissemination of this communication is
strictly prohibited by Commonwealth law. If you have received this transmission in error,
please notify the sender immediately by e-mail or by telephoning +61 3 6232 3209 and
DELETE the message.
        Visit our web site at http://www.antarctica.gov.au/
___________________________________________________________________________



More information about the R-help mailing list