假设我使用 gsub 并希望从字符串中删除以下 (=,+,-) 符号并替换为下划线。
有人可以描述当我尝试使用带加号 (+) 的 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_"
Try
test<- "sandwich=bread-mustard+ketchup"
test<-gsub("\\+","_",test)
test
[1] "sandwich=bread-mustard_ketchup"
+
是一个特殊字符。你需要逃避它。与例如相同,.
。如果你用谷歌搜索regex
或者正则表达式,您将找到相应的特殊字符列表。例如,here http://regexlib.com/CheatSheet.aspx?AspxAutoDetectCookieSupport=1 +
被描述以表明1 or more of previous expression
。有关特殊字符、正则表达式和 R 的更多信息,请参阅here https://stat.ethz.ch/R-manual/R-devel/library/base/html/regex.html or here https://stackoverflow.com/questions/27721008/how-do-i-deal-with-special-characters-like-in-my-regex.
更一般地说,可以使用以下方法更有效地编写上述代码:
test<- "sandwich=bread-mustard+ketchup"
test<-gsub("[-|=|\\+]","_",test)
test
[1] "sandwich_bread_mustard_ketchup"
这里我使用了一个基本上可以读作的结构[either this or that or something else]
, where |
对应于or
.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)