>>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)))
}


 is.constant(rep(c(sin(pi/2),1),10)) # TRUE
 x <- factor(c(1,1,NA))
 is.constant(x)            # FALSE because of NA
 is.constant(x[1:2])       # TRUE
 is.constant(c(1,1,NA))    # FALSE because of NA
 is.constant(c(1,1,2))     # FALSE
 is.constant(c(1,1,1))     # TRUE

--
Dr.sc.math.Christian W. Hoffmann, http://www.wsl.ch/staff/christian.hoffmann
Mathematics + Statistical Computing e-mail: [EMAIL PROTECTED]
Swiss Federal Research Institute WSL Tel: ++41-44-73922- -77 (office)
CH-8903 Birmensdorf, Switzerland -11(exchange), -15 (fax)


______________________________________________
[EMAIL PROTECTED] mailing list
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide! http://www.R-project.org/posting-guide.html

Reply via email to