R中的gsub()不会替换'.' (点) [英] gsub() in R is not replacing '.' (dot)

查看:661
本文介绍了R中的gsub()不会替换'.' (点)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将"2014.06.09"中的点替换为"2014-06-09".我正在使用 gsub()函数.如果

I want to replace dots in "2014.06.09" to "2014-06-09". I am using gsub() function for it. If

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

但是当我尝试

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

而不是"2014-06-09".

class(x)
# "character"

有人可以建议我做一个正确的方法,以及为什么它不适用于'.'(点)

Can some suggest me a way to get this right and also why it is not working for '.' (dot)

推荐答案

您可能需要转义.,这是一个特殊字符,表示任何字符"(来自@Mlick Flick的评论)

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"

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

或者如评论中提到的@Moix一样,我们也可以使用fixed=TRUE代替转义字符.

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

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

这篇关于R中的gsub()不会替换'.' (点)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆