paranormaldist
paranormaldist

Reputation: 508

R dataframe column replace only first space before a comma with underscore

Similarly worded questions, but not quite what I'm looking for and am a bit stuck. I have a column of "City, State " values. Some cities have 2 words, like "Grand Rapids, MI". I would like to replace that first space so it becomes Grand_Rapids, MI. I'm using separate to create City and State values so I would like to keep the space between City and State. How can I do so?

Col1
Fort Myers, FL
Grand Rapids, MI

becomes

Col1
Fort_Myers, FL
Grand_Rapids, MI

So that I can use

df1 <- df%>%separate(Col1,c("City","State"))

to get

City         State
Fort_Myers     FL
Grand_Rapids   MI

Upvotes: 0

Views: 220

Answers (1)

akrun
akrun

Reputation: 887571

We can use the sep here or else it could match other delimiters i.e. the space between the 'Fort' and 'Myers' as well (or if it is _)

library(dplyr)
library(tidyr)
df %>%
    separate(Col1,c("City","State"), sep=",\\s*")

Upvotes: 1

Related Questions