如何从 R 中的字符串中删除 +(加号)?
How to remove + (plus sign) from string in R?
假设我使用 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_"
尝试
test<- "sandwich=bread-mustard+ketchup"
test<-gsub("\+","_",test)
test
[1] "sandwich=bread-mustard_ketchup"
+
是一个特殊字符。你需要逃避它。与例如 .
相同。如果你用 google regex
或正则表达式,你会发现相应的特殊字符列表。例如,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.
更笼统地说,您可以使用以下代码更有效地编写上述代码:
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)
感谢 Jota
我也卡住了。以下代码对我有用。
test<- "sandwich=bread-mustard+ketchup"
test<-gsub("\+","_",test)
test
[1] "sandwich=bread-mustard_ketchup"
然而,有一次没有奏效。我试过 Ian's solution 。成功了。
假设我使用 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_"
尝试
test<- "sandwich=bread-mustard+ketchup"
test<-gsub("\+","_",test)
test
[1] "sandwich=bread-mustard_ketchup"
+
是一个特殊字符。你需要逃避它。与例如 .
相同。如果你用 google regex
或正则表达式,你会发现相应的特殊字符列表。例如,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.
更笼统地说,您可以使用以下代码更有效地编写上述代码:
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)
感谢 Jota
我也卡住了。以下代码对我有用。
test<- "sandwich=bread-mustard+ketchup"
test<-gsub("\+","_",test)
test
[1] "sandwich=bread-mustard_ketchup"
然而,有一次没有奏效。我试过 Ian's solution 。成功了。