如何从R中的字符串中删除+(加号)?
问题描述:
说我使用gsub,并希望从字符串中删除以下(=,+, - )符号并用下划线替换。如何从R中的字符串中删除+(加号)?
有人可以描述当我尝试使用带有加号(+)的gsub时发生了什么。
test<- "sandwich=bread-mustard+ketchup"
# [1] "sandwich=bread-mustard+ketchup"
test<-gsub("-","_",test)
# [1] "sandwich=bread_mustard+ketchup"
test<-gsub("=","_",test)
# [1] "sandwich_bread_mustard+ketchup"
test<-gsub("+","_",test)
#[1] "_s_a_n_d_w_i_c_h___b_r_e_a_d___m_u_s_t_a_r_d_+_k_e_t_c_h_u_p_"
答
尝试
test<- "sandwich=bread-mustard+ketchup"
test<-gsub("\\+","_",test)
test
[1] "sandwich=bread-mustard_ketchup"
+
是一个特殊字符。你需要逃避它。与例如.
相同。如果你的谷歌regex
或正则表达式,你会发现相应的特殊字符列表。例如,here+
被描述为指示1 or more of previous expression
。有关特殊字符的更多信息,可以找到正则表达式和R或here。
在更一般的笔记,你上面的代码可以更有效地使用被写入:
test<- "sandwich=bread-mustard+ketchup"
test<-gsub("[-|=|\\+]","_",test)
test
[1] "sandwich_bread_mustard_ketchup"
在这里,我已经使用了基本上可以理解为[either this or that or something else]
,其中|
对应or
的构造。
答
test<-gsub("+","_",test,fixed = TRUE)
信贷霍塔
+0
这比使用'\\ +'没有'fixed = TRUE'快。 –
您可以设置'固定= TRUE'或难逃 “+”。 – Jota
太棒了,谢谢它的工作! – Jonathan
在我看来,R是一个弱的正则表达式平台。如果你的大部分工作都属于这种类型,那么学习bash正则表达式工具和/或Perl是值得的。 – Novice