[R] ifelse statement

Duncan Murdoch murdoch.duncan at gmail.com
Thu Jul 8 01:22:10 CEST 2010


On 07/07/2010 5:58 PM, karena wrote:
> Hi, I am a newbie of R, and playing with the "ifelse" statement.
>
> I have the following codes:
> ## first,
>
> for(i in 1:3) {
> for(j in 2:4) {
> cor.temp <- cor(iris.allnum[,i], iris.allnum[,j])
> if(i==1 & j==2) corr.iris <- cor.temp
> else corr.iris <- c(corr.iris, cor.temp)
> }
> }
>
> this code is working fine.
>
> I also tried to perform the same thing in another way with "ifelse":
> for(i in 1:3) {
> for(j in 2:4) {
> cor.temp <- cor(iris.allnum[,i], iris.allnum[,j])
> corr.iris <- ifelse(i==1 & j==2, cor.temp, c(corr.iris, cor.temp))
> }
> }
>
> This is not working. Seems the value of "c(corr.iris, cor.temp)" has not
> been assigned to corr.iris, even  when the (i==1 & j==2) is not satisfied.
>
> what's the problem here?


See ?ifelse.  It computes something the same shape as the test object.  
In your case the test is the result of

i==1 & j==2

and is a scalar that is either TRUE or FALSE, so the result of ifelse() 
will be a scalar too.

To do what you want in one line, you can use

corr.iris <- if (i==1 && j==2) cor.temp else c(corr.iris, cor.temp)

but to most people this looks unnatural, and your original code is what I'd recommend using.  In this case it makes no difference whether you use & or && in the test, but in other cases only && makes sense with if, and only & makes sense with ifelse().

Duncan Murdoch



More information about the R-help mailing list