How to remove + (plus sign) from string in R?

Viewed 20481

Say I use gsub and want to remove the following (=,+,-) sign from the string and replace with an underscore.

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_"
3 Answers

I was also stuck. the following code worked for me.

test<- "sandwich=bread-mustard+ketchup"
test<-gsub("\\+","_",test)
test
[1] "sandwich=bread-mustard_ketchup"

However, one time it didn't work. I tried with Ian's solution . It worked.

Related