# [R] ifelse on data frames

Henric Nilsson henric.nilsson at statisticon.se
Mon Jan 8 09:33:26 CET 2007

```maj at stats.waikato.ac.nz said the following on 2007-01-05 04:18:

> [Using R 2.2.0 on Windows XP; OK, OK, I will update soon!]
>
> I have noticed some undesirable behaviour when applying
> ifelse to a data frame. Here is my code:
>
> A <- scan()
>  1.000000 0.000000 0.000000  0 0.00000
>  0.027702 0.972045 0.000253  0 0.00000
>
> A <- matrix(A,nrow=2,ncol=5,byrow=T)
> A == 0
> ifelse(A==0,0,-A*log(A))
>
> A <- as.data.frame(A)
> ifelse(A==0,0,-A*log(A))

sapply(A, function(x) ifelse(x == 0, 0, -x*log(x)))

?

HTH,
Henric

>
> and this is the output:
>
>> A <- scan()
> 1:  1.000000 0.000000 0.000000  0 0.00000
> 6:  0.027702 0.972045 0.000253  0 0.00000
> 11:
>> A <- matrix(A,nrow=2,ncol=5,byrow=T)
>> A == 0
>       [,1]  [,2]  [,3] [,4] [,5]
> [1,] FALSE  TRUE  TRUE TRUE TRUE
> [2,] FALSE FALSE FALSE TRUE TRUE
>> ifelse(A==0,0,-A*log(A))
>            [,1]       [,2]        [,3] [,4] [,5]
> [1,] 0.00000000 0.00000000 0.000000000    0    0
> [2,] 0.09934632 0.02756057 0.002095377    0    0
>> A <- as.data.frame(A)
>> ifelse(A==0,0,-A*log(A))
> []
>  0.00000000 0.09934632
>
> []
>         NaN 0.02756057
>
> []
>  0
>
> []
>  NaN NaN
>
> []
>  0
>
> []
>  0.00000000 0.09934632
>
> []
>  0
>
> []
>  0
>
> []
>  0
>
> []
>  0
>
>
> Is this a bug or a feature? Can the behaviour be explained?
>
> Regards,  Murray Jorgensen

```