Hi,

The parentheses are in the wrong places in the two if() statements.

Look here:

(length(table(x)>1))
            ^                ^
(length(table(x)==1))
            ^                 ^

In both cases you're checking whether
the length of the comparison (table(x) > 1) or (table(x) == 1)
is 1, which it always is regardless of whether the
comparison itself is true or false. If you move those, it
should be fine. Although I think I'd use length(unique(x)) instead.

Sarah

On Thu, Feb 23, 2012 at 9:19 AM, Jonathan Williams
<jonathan.willi...@dpag.ox.ac.uk> wrote:
> Dear Helpers,
>
> I wrote a simple function to standardise variables if they contain more than 
> one value. If the elements of the variable are all identical, then I want the 
> function to return zero.
>
> When I submit variables whose elements are all identical to the function, it 
> returns not zero, but NaNs.
>
> zt=function(x){if (length(table(x)>1)) y=(x-mean(x))/sd(x) else if 
> (length(table(x)==1)) y=0; return(y)}
>
> zt(c(1:10))
> #[1] -1.4863011 -1.1560120 -0.8257228 -0.4954337 -0.1651446  0.1651446  
> 0.4954337  0.8257228  1.1560120  1.4863011
>
> zt(rep(1,10))
> #[1] NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN
>
> Would you be so kind as to point out what I am doing wrong, here? How can I 
> obtain zeros from my function, instead of NaNs? (I obtain NaNs also if I set 
> the function to zt=function(x){if (length(table(x)>1)) y=(x-mean(x))/sd(x) 
> else if (length(table(x)==1)) y=rep(0, length(x)); return(y)} ).
>
> Thanks, in advance, for your help,
>
> Jonathan Williams
>
> __

-- 
Sarah Goslee
http://www.functionaldiversity.org

______________________________________________
R-help@r-project.org mailing list
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.

Reply via email to