Reputation: 161
I just want to replace some word separators with a space. Any hints on this? Doesn't work after converting to character either.
df <- data.frame(m = 1:3, n = c("one.one", "one.two", "one.three"))
> gsub(".", "\\1 \\2", df$n)
[1] " " " " " "
> gsub(".", " ", df$n)
[1] " " " " " "
Upvotes: 0
Views: 64
Reputation: 99351
You don't need to use regex for one-to-one character translation. You can use chartr()
.
df$n <- chartr(".", " ", df$n)
df
# m n
# 1 1 one one
# 2 2 one two
# 3 3 one three
Upvotes: 4
Reputation: 132949
Set fixed = TRUE
if you are looking for an exact match and don't need a regular expression.
gsub(".", " ", df$n, fixed = TRUE)
#[1] "one one" "one two" "one three"
That's also faster than using an appropriate regex for such a case.
Upvotes: 2
Reputation: 887571
You can try
gsub("[.]", " ", df$n)
#[1] "one one" "one two" "one three"
Upvotes: 2
Reputation: 174796
I suggest you to do like this,
gsub("\\.", " ", df$n)
OR
gsub("\\W", " ", df$n)
\\W
matches any non-word character. \\W+
matches one or more non-word characters. Use \\W+
if necessary.
Upvotes: 1