Created
September 14, 2012 01:45
-
-
Save inkhorn/3719319 to your computer and use it in GitHub Desktop.
Find the second highest value in a vector
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
penultimax = function(invector) { | |
# If the vector starts off as only having 1 or 0 numbers, return NA | |
if (length(invector) <= 1) { | |
return(NA) | |
} | |
first.max = safe.max(invector) | |
#Once we get the max, take it out of the vector and make newvector | |
newvector = invector[!invector == first.max] | |
#If newvector now has nothing in it, return NA | |
if (length(newvector) == 0) { | |
return(NA) | |
} | |
#Now we get the second highest number in the vector. | |
#So long as it's there, we return that second highest number (the penultimax) | |
#or else we just return NA | |
second.max = safe.max(newvector) | |
if (is.na(first.max) & is.na(second.max)) { | |
return (NA) } | |
else if (!is.na(first.max) & is.na(second.max)) { | |
return (NA) } | |
else if (!is.na(first.max) & !is.na(second.max)) { | |
return (second.max)} | |
} | |
safe.max = function(invector) { | |
na.pct = sum(is.na(invector))/length(invector) | |
if (na.pct == 1) { | |
return(NA) } | |
else { | |
return(max(invector,na.rm=TRUE)) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment