Search code examples
rcsvstrsplit

How to Split a String into two different elements in R?


I have a string like

c <- "Gary INMetro Chicago IL Metro"

I am doing

d <- strsplit(c,"Metro")

to get

> d[1]
[[1]]
[1] "Gary IN" " Chicago IL "

But I want two different elements and want to write to the csv file as

 City,State
 Gary,IN
 Chicago,IL

How to do that? Any help is appreciated.


Solution

  • Try this:

    read.table(text=gsub('Metro', '\n', c), col.names=c('City', 'State'))
    #      City State
    # 1    Gary    IN
    # 2 Chicago    IL