1
$\begingroup$

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?

$\endgroup$
1
$\begingroup$

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"

| improve this answer | |
$\endgroup$
  • $\begingroup$ Worked perfectly :) Thank you! $\endgroup$ – Greation May 9 '19 at 13:09
0
$\begingroup$

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.

| improve this answer | |
$\endgroup$

Not the answer you're looking for? Browse other questions tagged or ask your own question.