I have a dataframe with the following column
city <- c("Sydney NSW", "Newcastle NSW", "Liverpool NSW", "Broken Hill NSW")
I want to maintain everything prior to NSW
(space included). What Regex expression can be used in R for that?
Data Science Stack Exchange is a question and answer site for Data science professionals, Machine Learning specialists, and those interested in learning more about the field. It only takes a minute to sign up.
Sign up to join this communityI have a dataframe with the following column
city <- c("Sydney NSW", "Newcastle NSW", "Liverpool NSW", "Broken Hill NSW")
I want to maintain everything prior to NSW
(space included). What Regex expression can be used in R for that?
Use strsplit()
.
If you want to remove the space between the two words (along with 'NSW'):
city_clean <- unlist(c(strsplit(city, " NSW")))
Output: [1] "Sydney" "Newcastle" "Liverpool" "Broken Hill"
It wasn't clear to me whether you wanted to keep the space or not. If you want to keep the trailing space after the city name
city_clean <- unlist(c(strsplit(city, "NSW")))
Output: [1] "Sydney " "Newcastle " "Liverpool " "Broken Hill "
If you prefer to use regex, here's another solution:
city_clean <- gsub(" NSW", "", city)
Output: [1] "Sydney" "Newcastle" "Liverpool" "Broken Hill"
In base R you could use
gsub("NSW$", "", city)
This function is vectorized and performs the replacement in all elements of the vector.
With the tidyverse package stringr
you could use the vectorized function str_replace
:
library(stringr)
str_replace(city, "NSW$", "")
Here the order of arguments is more natural, in my opinion.
stringr
depends on stringi
. If you have to install these packages first, it will take a while because R will compile a lot of helper C/C++ code during installation.