Created
June 25, 2019 09:50
-
-
Save almogsi/bd23a2509b29e6823defa5504545da9f to your computer and use it in GitHub Desktop.
function for classifying States' political affiliation
This file contains hidden or 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
| cat_state <- function(a, abbreviation=F) { | |
| Swing = c("Wisconsin", "Virginia", "Michigan", "Pennsylvania", | |
| "New Hampshire", "Colorado", "Nevada", "North Carolina", | |
| "Florida", "Ohio", "Arizona", "Iowa", "Georgia") | |
| Swing_abb = state.abb[match(Swing,state.name)] | |
| Democrat = c("New Mexico", "Minnesota", "Maine", "Oregon", | |
| "New Jersey", "Delaware", "Connecticut", "Illinois", | |
| "Washington", "Rhode Island", "New York", "California", | |
| "Massachusetts", "Hawaii", "Maryland", "Vermont") | |
| Democrat_abb = state.abb[match(Democrat,state.name)] | |
| Democrat_abb = c("DC",Democrat_abb) | |
| Democrat_full = c("District of Columbia", Democrat) | |
| Republican = c("Nebraska", "South Carolina", "Texas", "Missouri", | |
| "Utah", "Indiana", "Tennessee", "Kansas", "Mississippi", | |
| "Montana", "South Dakota", "Louisiana", "Kentucky", "Idaho", | |
| "Arkansas", "Alabama", "North Dakota", | |
| "Oklahoma", "West Virginia", "Wyoming", "Alaska") | |
| Republican_abb = state.abb[match(Republican,state.name)] | |
| all_names = c(Republican, Swing, Democrat_full) | |
| all_abb = c(Swing_abb, Democrat_abb, Republican_abb) | |
| #ifelse(as.numeric(match(a, Swing_abb))>0, cat="Swing", ifelse(as.numeric(match(a, Democrat_abb))>0, cat="Democrat", cat="Republican")) | |
| if (abbreviation == T) { | |
| if (is.na(match(tolower(a), tolower(all_abb)))) { | |
| return("Error! no such abbreviation") | |
| } | |
| else { | |
| if (is.na(match(tolower(a), tolower(Swing_abb))) && is.na(match(tolower(a), tolower(Democrat_abb)))){ | |
| cat = "Republican" | |
| } | |
| else if (is.na(match(tolower(a), tolower(Swing_abb))) && is.na(match(tolower(a), tolower(Republican_abb)))){ | |
| cat = "Democrat" | |
| } | |
| else { | |
| cat = "Swing" | |
| } | |
| } | |
| return(cat) | |
| } | |
| else { | |
| if (is.na(match(tolower(a), tolower(all_names)))) { | |
| return("Error! no such state!") | |
| } | |
| else { | |
| if (is.na(match(tolower(a), tolower(Swing))) & is.na(match(tolower(a), tolower(Democrat_full)))){ | |
| cat = "Republican" | |
| } | |
| else if (is.na(match(tolower(a), tolower(Swing))) & is.na(match(tolower(a), tolower(Republican)))){ | |
| cat = "Democrat" | |
| } | |
| else { | |
| cat = "Swing" | |
| } | |
| return(cat) | |
| }} } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment