0

I have a column of data with strings that have spaces - some strings have a single space and some have multiple (eg. X Y vs X Y Z). The code segment below worked well for a single space removal (making X Y to X_Y) but doesn't seem to work for multiple spaces - X Y Z becomes X_Y Z.

all_data$`Facility Name` <- str_replace(all_data$`Facility Name`, pattern = " ", replacement = "_")
Martin Gal
  • 16,640
  • 5
  • 21
  • 39
  • 1
    Please add a language-specific tag. – PM 77-1 Nov 14 '21 at 23:02
  • `str_replace()` implies PHP; I have added this tag for you. Please update it if it is not correct. – Obsidian Age Nov 14 '21 at 23:03
  • Please make a [reproducible example](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) or [minimal reproducible example](https://stackoverflow.com/help/minimal-reproducible-example) with a sample input and your expected output. This is needed to create, test and verify possible solutions. – Martin Gal Nov 16 '21 at 16:26

2 Answers2

0

You can try to do this :

$a = 'X Y Z T';

$r = preg_replace('/\s/', '_', $a);

var_dump($r);

And the result will be :

string(7) "X_Y_Z_T"

glitchcl
  • 318
  • 2
  • 9
0

Use str_replace_all:

library(stringr)
all_data$`Facility Name` <- str_replace_all(all_data$`Facility Name`, pattern = " ", replacement = "_")

Example:

x <- c("A B", "A B A", "A", "A B A C D")
str_replace_all(x, pattern = " ", replacement = "_")
[1] "A_B"       "A_B_A"     "A"         "A_B_A_C_D"
Chris Ruehlemann
  • 20,321
  • 4
  • 12
  • 34