[R] FW: NaN from function

Petr Savicky savicky at cs.cas.cz
Thu Feb 23 17:57:27 CET 2012


On Thu, Feb 23, 2012 at 04:40:07PM -0000, Ted Harding wrote:
[...]
> A basic solution for this special case would be
> 
>   zt=function(x){
>     if (sd(x) == 0) return(0*x) else return( (x-mean(x))/sd(x) )
>   }
> 
> This should cover the case where length(table(x))==1 (see also below).
> 
> I'm not happy about your conditions
> 
>   if (length(table(x)>1))
>   if (length(table(x)==1))
> 
> since they ask for "length(table(x)>1)", which doesn't seem
> to represent any natural criterion. E.g.:
> 
>   length(table(1:10)>1)
>   # [1] 10
>   length(table(rep(1,10))>1)
>   # [1] 1
> 
>   if(length(table(1:10)>1)) y <- "Yes" else y <- "No" ; y
>   # [1] "Yes"
>   if(length(table(rep(1,10))>1)) y <- "Yes" else y <- "No" ; y
>   # [1] "Yes"
> 
>   length(table(1:10)==1)
>   # [1] 10
>   length(table(rep(1,10))==1)
>   # [1] 1
>   
>   if(length(table(1:10)==1)) y <- "Yes" else y <- "No" ; y
>   # [1] "Yes"
>   if(length(table(rep(1,10))==1)) y <- "Yes" else y <- "No" ; y
>   # [1] "Yes"
> 
> I suspect you meant to write
> 
>   if (length(table(x))>1)
> and
>   if (length(table(x)))==1)
> 
> since this distinguishes between two more more different values
> (length(table(x)) > 1) and all equal values (length(table(x)) == 1).

Hi.

The condition length(table(x)) > 1 may also be written as
lentgh(unique(x)) > 1. These two conditions are usually
equivalent, but not always due to the rounding to 15 digits
performed in table(). For example

  x <- 1 + (0:10)*2^-52
  length(table(x))  # [1] 1
  length(unique(x)) # [1] 11
  sd(x)             # [1] 7.364386e-16
  diff(x)           # [1] 2.220446e-16 2.220446e-16 2.220446e-16 ...

Petr Savicky.



More information about the R-help mailing list