[R] (no subject)
Petr PIKAL
petr.pikal at precheza.cz
Thu Feb 23 15:50:42 CET 2012
Hi
>
> 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.
R's scale function is intended to do such things.
zt2 <- function(x) as.numeric(ifelse(is.nan(scale(x)), 0, scale(x)))
Regards
Petr
>
> Sarah
>
> On Thu, Feb 23, 2012 at 9:19 AM, Jonathan Williams
> <jonathan.williams at 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 at 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.
More information about the R-help
mailing list