[R] is.constant 2
Gabor Grothendieck
ggrothendieck at myway.com
Wed Sep 22 14:16:10 CEST 2004
Christian Hoffmann <christian.hoffmann <at> wsl.ch> writes:
>
> >>x <- c(1, 2, NA)
> >>>>is.constant(x)
> >
> >>
> >> [1] TRUE
> >>
> >> For data such as c(1, 1, 1, NA), I should think the safest answer
> should be
> >> NA, because one really doesn't know whether that last number is 1 or
> not.
> >>
> >> Andy
> >>
>
> >My version is
> >is.constant <- function(x) {
> > if (is.numeric(x) & !any(is.na(x))) identical(min(x), max(x)) else
> >FALSE
> >}
>
> Since the issue of factors surfaced, I improved my function:
>
> is.constant <- function(x) {
> if (is.factor(x)) (length(attributes(x)$levels)==1) &&
> (!any(is.na(as.character(x))))
> else (is.numeric(x) && !any(is.na(x)) && identical(min(x), max(x)))
> }
Suggest you use an S3 generic and a separate methods for factor, and
in the future, other classes. Also to make it more consistent with
other R functions have an na.rm= argument which defaults to TRUE.
If na.rm = FALSE then it should return NA there are any NAs in
the same way that sum(c(1,2,NA), na.rm = FALSE) returns NA. There is
some question of how to handle zero length arguments (or ones
that become zero length after removing NAs).
is.constant <- function(x, ...) UseMethod("is.constant")
is.constant.factor <- function(x, na.rm = TRUE) ... code for factor ...
is.constant.default <- function(x, na.rm = TRUE) ... code for default ...
More information about the R-help
mailing list