R 中的 gsub()不会替换’。’(点)

我想替换点在 "2014.06.09""2014-06-09"。我使用 Gsub ()的功能。如果

x <-  "2014.06.09"
gsub('2', '-' ,x)
# [1] "-014.06.09"

但当我尝试

gsub('.', '-', x)
# [1] "----------"

而不是 "2014-06-09"

class(x)
# "character"

可以一些建议我的方法来得到这个权利,也为什么它是不工作的 '.'(点)

102266 次浏览

You may need to escape the . which is a special character that means "any character" (from @Mr Flick's comment)

 gsub('\\.', '-', x)
#[1] "2014-06-09"

Or

gsub('[.]', '-', x)
#[1] "2014-06-09"

Or as @Moix mentioned in the comments, we can also use fixed=TRUE instead of escaping the characters.

 gsub(".", "-", x, fixed = TRUE)

For more complex tasks the stringr package could be interesting

https://cran.r-project.org/web/packages/stringr/vignettes/stringr.html

https://github.com/rstudio/cheatsheets/raw/master/strings.pdf

library(stringr)


str_replace_all(x,"\\.","-")
## [1] "2014-06-09"

Or

str_replace_all(x,"[.]","-")
## [1] "2014-06-09"

Using raw strings, introduced in R 4.0.0, one could do

gsub(r"(\.)", "-", x)
# [1] "2014-06-09"