Reputation: 149
I have a string that is
NAME = "Brad.Pitt"
I want to replace "." with a space (" "). I tried using sub, gsub, str_replace, str_replace all. They aren't working fine. Is there anything that I am missing out ?
Upvotes: 1
Views: 4414
Reputation: 269714
The main thing missing is that all the commands you mention regard the pattern as a regular expression, not a fixed string and, in particular, in a regular expression dot matches any character -- not just dot. You can find out more about these by reading ?"regular expression"
Here are some alternatives. (1) The first one uses fixed=TRUE
so that the special characters in the first argument are not interpreted as regular expression characters. We used sub
which substitutes one occurrence but if there were multiple occurrences and you wanted to replace them all with space then use gsub
in place of sub
. (2) The second escapes the dot with square brackets so it is not interpreted as a regular expression character. Another way of escaping dot is to preface it with a backslash so using R 4.0 r"{...}" notation we can use r"{\.}"
as the pattern or without that notation see the other answer. (3) chartr
does not use regular expressions at all. It will replace every dot with space. (4) substr<-
replaces the 5th character with space. (5) scan
read in the words separately creating a character vector with two components and then paste
pastes them back together with a space between them. If there were multiple dots then it would replace each with a space.
# 1
sub(".", " ", NAME, fixed = TRUE)
## [1] "Brad Pitt"
# 2
sub("[.]", " ", NAME)
## [1] "Brad Pitt"
# 3
chartr(".", " ", NAME)
## [1] "Brad Pitt"
# 4
`substr<-`(NAME, 5, 5, ' ')
## [1] "Brad Pitt"
# 5
paste(scan(text = NAME, what = "", sep = ".", quiet = TRUE), collapse = " ")
## [1] "Brad Pitt"
Also note that if the reason you have the dot is that you read it in as a heading then you can use check.names = FALSE
to avoid that. Compare the headings in the output of the two read.csv
commands below.
Lines <- "BRAD PITT
1
2"
read.csv(text = Lines)
## BRAD.PITT
## 1 1
## 2 2
read.csv(text = Lines, check.names = FALSE)
## BRAD PITT
## 1 1
## 2 2
Upvotes: 3