如何从R中的字符串中删除+(加号)? [英] How to remove + (plus sign) from string in R?
问题描述
说我使用gsub并想从字符串中删除以下(=,+,-)符号并替换为下划线.
Say I use gsub and want to remove the following (=,+,-) sign from the string and replace with an underscore.
有人可以描述当我尝试使用带加号(+)的gsub时发生了什么.
Can someone describe what is going on when I try to use the gsub with a plus sign (+).
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"
+
是一个特殊字符.您需要逃脱它.例如,与.
相同.如果您使用Google regex
或正则表达式,则会找到相应的特殊字符列表.例如,描述此处 +
表示1 or more of previous expression
.有关特殊字符,正则表达式和R的更多信息,请参见此处或此处.
+
is a special character. You need to escape it. Same as, for instance, .
. If you google regex
or regular expressions, you will find the corresponding lists of special characters. For instance, here +
is described to indicate 1 or more of previous expression
. More about special characters, regular expressions and R can be found here or here.
一般来说,使用以下代码可以更有效地编写您的上述代码:
On a more general note, your above code could be written more efficiently by using:
test<- "sandwich=bread-mustard+ketchup"
test<-gsub("[-|=|\\+]","_",test)
test
[1] "sandwich_bread_mustard_ketchup"
在这里,我使用的结构基本上可以理解为[either this or that or something else]
,其中|
对应于or
.
Here I have used a construct that can basically be read as [either this or that or something else]
, where |
corresponds to or
.
这篇关于如何从R中的字符串中删除+(加号)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!