Exc
Exc

Reputation: 183

Move location of special character

I have an entire vector of strings with the only special symbol in them being "-"

To be clear a sample string is like 23 C-Exam

I'd like to change it 23-C Exam

I essentially want R to find the location of "-" and move it 2 spaces back.

I feel this is a really simple task although I cant figure out how.

Assume that whenever R finds "-" , two spaces back is whitespace just like the example above.

Upvotes: 2

Views: 43

Answers (3)

akrun
akrun

Reputation: 887711

We can also use chartr

chartr(" -", "- ", x)
#[1] "23-C Exam" "45-D Exam"

data

x <- c("23 C-Exam","45 D-Exam")

Upvotes: 1

thelatemail
thelatemail

Reputation: 93938

regex attempt:

x <- c("23 C-Exam","45 D-Exam")
#[1] "23 C-Exam" "45 D-Exam"
sub(".(.)-", "-\\1 ", x)
#[1] "23-C Exam" "45-D Exam"

Find a character ., before a character (.), followed by a literal dash -.
Replace with a literal dash -, the saved character from above \\1, and overwrite the dash with a space

Upvotes: 3

Tim Biegeleisen
Tim Biegeleisen

Reputation: 522506

There is probably a sleek way of doing this with regular expressions, but one approach is to simply splice together the various pieces of the desired output. First, I find the index in the string containing the -, and then I use substr() to piece together the output.

pos <- regexpr("-", "23 C-Exam")
x <- "23 C-Exam"

x <- paste0(substr(x, 1, pos-3),
            "-",
            substr(x, pos-1, pos-1),
            " ",
            substr(x, pos+1, nchar(x)))

> x
[1] "23-C Exam"

Upvotes: 2

Related Questions