Replace specific characters within strings
With a regular expression and the function gsub()
:
group <- c("12357e", "12575e", "197e18", "e18947")group[1] "12357e" "12575e" "197e18" "e18947"gsub("e", "", group)[1] "12357" "12575" "19718" "18947"
What gsub
does here is to replace each occurrence of "e"
with an empty string ""
.
See ?regexp
or gsub
for more help.
Regular expressions are your friends:
R> ## also adds missing ')' and sets column nameR> group<-data.frame(group=c("12357e", "12575e", "197e18", "e18947")) )R> group group1 12357e2 12575e3 197e184 e18947
Now use gsub()
with the simplest possible replacement pattern: empty string:
R> group$groupNoE <- gsub("e", "", group$group)R> group group groupNoE1 12357e 123572 12575e 125753 197e18 197184 e18947 18947R>
Summarizing 2 ways to replace strings:
group<-data.frame(group=c("12357e", "12575e", "197e18", "e18947"))
1) Use gsub
group$group.no.e <- gsub("e", "", group$group)
2) Use the stringr
package
group$group.no.e <- str_replace_all(group$group, "e", "")
Both will produce the desire output:
group group.no.e1 12357e 123572 12575e 125753 197e18 197184 e18947 18947