I have state and county names in a single string variable states_county, and I want to split them to create two distinct variables - states and county.
Some states have two (or even three words), and the same goes for counties.
> states_county_names_df$states_county
[1] "California San Francisco"
[2] "New York Bronx"
[3] "New York Kings"
[4] "New York New York"
[5] "New York Queens"
[6] "New York Richmond"
[7] "Washington King"
[8] "Illinois Cook"
[9] "Massachusetts Suffolk"
[10] "District of Columbia District of Columbia"
Thus, I want to pull in names of all US states to create a factor variable and use a substring command to remove the states (and get counties), while also only keeping the states (to remove the counties). I am not sure how to loop each factor variable level for each string entry in my states_county variable though.
state_name<-state.name
for(i in levels(state_name)){
print("levels(state_name)")
test<-str_remove_all(states_county_names_df$states_county, "levels(state_name)")
}
Would appreciate if anyone could suggest different ways to get the result.
I currently use brute force and write a 50 lines of code to generate a state column, but still cannot get to counties as I am not sure how to "substract" the state column from states_county column.
states_county_names_df$states[grepl("California",states_county_names_df$states_county)] <- "California"
states_county_names_df$states[grepl("New York", states_county_names_df$states_county)] <- "New York"
.
.
.