Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
724 views
in Technique[技术] by (71.8m points)

r - Replace two dots in a string with gsub

I'm trying to use the following code to replace two dots for only one:

test<-"test..1"
gsub("\..", ".", test, fixed=TRUE)

and getting:

[1] "test..1"

I tried several combinations of escape strings, including brackets [] with no success.
What am I doing wrong?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

If you are going to use fixed = TRUE, use the (non-interpreted) character .:

> gsub("..", ".", test, fixed = TRUE)

Otherwise, within regular expressions (fixed = FALSE), . has a special meaning (any character) so you'll want to prefix it with a backslash to mean "the dot character":

> gsub("\.\.", ".", test)
> gsub("\.{2}", ".", test)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...