Splitting Columns in R based on space

11,227
library(tidyr)

df <- data.frame(Location = c("San Jose CA", "Fremont CA", "Santa Clara CA"))
separate(df, Location, into = c("city", "state"), sep = " (?=[^ ]+$)")

#          city state
# 1    San Jose    CA
# 2     Fremont    CA
# 3 Santa Clara    CA
Share:
11,227
Mridul Garg
Author by

Mridul Garg

Updated on June 14, 2022

Comments

  • Mridul Garg
    Mridul Garg almost 2 years

    I have a Location Column which looks like the following-

       Location 
       San Jose CA
       Santa Clara CA
    

    I want to split into two columns. I'm using the separate function from tidyr, but giving the sep argument as " " gives me the following-

      City  State
      San   Jose
      Santa Clara
    

    How can I split the column based on only the second space?

    structure(list(Location = c("San Jose CA", "Santa Clara CA")),
              .Names = "Location", class = "data.frame", row.names = c(NA, -2L))