0

I've not been able to find a solution to a problem I'm dealing with in R. I have a data.frame with a column containing state and county separated by a space. The first two characters of every row in the column are the state. After the space, follows the county. I want to create two new columns with one being the state and the second being the county.

What I have:

VAR_A, VAR_B, ST_COUNTY
A, B, AZ MOVHAVE
A, B, NV ELKO
A, B, CA SAN BERNADINO

What I want:

VAR_A, VAR_B, ST,COUNTY
A, B, AZ, MOHAVE
A, B, NV, ELKO
A, B, CA, SAN BERNADINO

Let me know if anyone has some ideas on how to output a new data frame with the two new columns.

Thank you!

Sotos
  • 51,121
  • 6
  • 32
  • 66
Tony
  • 13
  • 4
  • You can use `substr` to get the first two characters and `substr` with `nchar` to get the remaining characters. – lmo Sep 15 '17 at 11:48
  • Can you supply some sample code so I can check it out? – Tony Sep 15 '17 at 11:58
  • Take a look at the help file for `?substr` to see what it does. As an example, try `substr(dat$ST_COUNTY, 1, 2)`. – lmo Sep 15 '17 at 12:02
  • @Jaap Not the best dupes, in my opinion, since `substr` would be more appropriate in this case. For example, consider "CA San Bernadino". – lmo Sep 15 '17 at 12:03
  • @lmo `df %>% separate(ST_COUNTY, c("ST","COUNTY"), sep = " ", extra = "merge")` works as expected (as is also explained in the 2nd link). – Jaap Sep 15 '17 at 12:18
  • Thanks for pointing that out. I always gloss over piped answers. – lmo Sep 15 '17 at 12:22
  • substr(dat$ST_COUNTY, 1, 2) works, thank you! – Tony Sep 15 '17 at 14:03

0 Answers0