Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get the strings before the comma with R

I am a beginner with R. Now, I have a vector in a data.frame like this

city
Kirkland,
Bethesda,
Wellington,
La Jolla,
Berkeley,
Costa, Evie KW172NJ
Miami,
Plano,
Sacramento,
Middletown,
Webster,
Houston,
Denver,
Kirkland,
Pinecrest,
Tarzana,
Boulder,
Westfield,
Fair Haven,
Royal Palm Beach, Fl
Westport,
Encino,
Oak Ridge,

I want to clean it. What I want is all the city names before the comma. How can I get the result in R? Thanks!

like image 899
user2855907 Avatar asked Oct 11 '13 14:10

user2855907


1 Answers

You can use gsub with a bit of regexp :

cities <- gsub("^(.*?),.*", "\\1", df$city)

This one works, too :

cities <- gsub(",.*$", "", df$city)
like image 133
juba Avatar answered Sep 20 '22 03:09

juba