简体   繁体   中英

R: str_replace not replacing characters, including special characters (+), within string?

How do I remove a " + " sign from a string?

I want to remove "d12$cig_tax + " from the following formula:

formula = "d12$r_hosp_tp ~ d12$cig_tax + d12$alc_tax + d12$air_temp + d12$x_67 + d12$x_t67 + d12$qs_67 + x_31 "

form2  <- str_replace(formula,paste0("d12$cig_tax"," [^[:alnum:]]")," ")
form2
[1] "d12$r_hosp_tp ~ d12$cig_tax + d12$alc_tax + d12$air_temp + d12$x_67 + d12$x_t67 + d12$qs_67 + x_31 "

What I would like it to return is form2 [1] "d12$r_hosp_tp ~ d12$alc_tax + d12$air_temp + d12$x_67 + d12$x_t67 + d12$qs_67 + x_31 "

This doesn't work either:

str_replace(formula,"d12$cig_tax"," ")
[1] "d12$r_hosp_tp ~ d12$cig_tax + d12$alc_tax + d12$air_temp + d12$x_67 + d12$x_t67 + d12$qs_67 + x_31 "

You want to replace based on a fixed string and not a regular expression. To prevent the second argument from being interpreted as a regular expression, use the fixed function.

str_replace(formula, fixed("d12$cig_tax + ")," ")
# [1] "d12$r_hosp_tp ~  d12$alc_tax + d12$air_temp + d12$x_67 + d12$x_t67 + d12$qs_67 + x_31 "

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM