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 [[alternative HTML version deleted]] ______________________________________________ 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.