Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace dots using `gsub`

Tags:

regex

r

gsub

I am trying to replace all the "." in a specific column of my data frame with "/". There are other characters in each cell and I want to make sure I only change the "."'s. When I use gsub, I get an output that appears to make the changes, but then when I go to View(), the changes are not actually made...I thought gsub was supposed to actually change the value in the data frame. Am I using it incorrectly? I have my code below.

gsub(".", "/", spy$Identifier, ignore.case = FALSE, perl = FALSE,
    fixed = TRUE, useBytes = FALSE)

I also tried sub, but the code I have below changed every entry itself to "/" and I am not sure how to change it.

spy$Identifier <- sub("^(.).*", "/", spy$Identifier)

Thanks!

like image 467
Mel Avatar asked Oct 21 '25 17:10

Mel


1 Answers

My recommendation would be to escape the "." character:

        spy$Identifier <- gsub("\\.", "/", spy$Identifier)

In regular expression, a period is a special character that matches any character. "Escaping" it tells the search to look for an actual period. In R's gsub this is accomplished with two backslashes (i.e.: "\\"). In other languages, it's often just one backslash.

like image 63
Evan Avatar answered Oct 23 '25 07:10

Evan