This function takes a numeric vector and returns "con" if it's continous and "bin" if it's binary.
It does not take the multinomial case into account, i.e. if a variable y has three possible values 0, 1, 2, it's treated like a continuous variable.
Code:
checkBinaryTrait = function(v, naVal="NA") {
if(!is.numeric(v)) stop("Only numeric vectors are accepted.")
vSet = unique(v)
if(!missing(naVal)) vSet[which(vSet == naVal)] = NA
vSet = vSet[which(!is.na(vSet))]
if(any(as.integer(vSet) != vSet)) return("con")
if(length(vSet) > 2) return("con")
"bin"
}
Tests:
v = c(1, 1.1, 1, 1.1, NA)
checkBinaryTrait(v)
v = c(1, 2, 1, 2, NA)
checkBinaryTrait(v)
v = c(-9, 2.3, 4.1, -9, -9)
checkBinaryTrait(v, -9)
v = c(-9, 2, 4, -9, -9)
checkBinaryTrait(v, -9)
NA
as a value too? \$\endgroup\$