Many values of my data frame are written differently although they were referring to the same value. I should change some of the column values to make them similar. I used stringr package str_replace_all, but it didn't work very well. It is not doing what I wanted it. Here is my reproducible data and the code.
df <- data.frame(
stringsAsFactors = FALSE,
Var1 = c("16-pathway","16a-OH E1",
"16a-OHE1","16OHE","17-b-estradiol","17-OH-progesterone",
"17-OH-progesterone/ androstenedione ratio",
"17b-HSD (rs2830A)","17b-HSD (rs592389 G)","17b-HSD (rs615492 G)",
"17b-HSD (rs615942 G)","17b estradiol",
"17OH-progesterone","2-hydroxy (OH) E1","2-OHE-1","2-OHE-2",
"2-pathway","2:16 OHE ratio","2:16 pathway ratio","2:16a-OH E1",
"2:16OHE","2OHE","Adiponectin","androstenedione",
"Androstenedione","androstenedione (A)"),
Freq = c(2L,1L,4L,8L,1L,6L,6L,2L,
2L,1L,1L,1L,5L,1L,4L,4L,2L,4L,2L,1L,8L,8L,
8L,1L,62L,1L)
)
library(stringr)
df$new_var1 <- str_replace_all(df$Var1,
c(#16OHE1
"16a-OH E1" = "16-OHE1",
"16a-OHE1" = "16-OHE1",
"16OHE" = "16-OHE1",
#17Beta estradiol
"17-b-estradiol" = "17-b-estradiol",
"17b estradiol"= "17-b-estradiol",
#Andreostenedione
"androstenedione" = "Androstenedione",
"Androstenedione" = "Androstenedione",
"androstenedione (A)" = "Androstenedione",
#2-OHE-1
"2-OHE-1" = "2-OHE-1",
"2-hydroxy (OH) E1" = "2-OHE-1")
)
Now, if you compare Var1 and new_var1, it didn't work to change "2-hydroxy (OH) E1" to "2-OHE-1" and "Androstenedione (A)" to "Androstenedione". See screenshots below.


stringrfunctions use regex, so you need to escape special characters like brackets, parentheses, and hyphens. If you don't want to use regex, the docs explain how to use fixed patterns: "Match a fixed string (i.e. by comparing only bytes), using fixed(). This is fast, but approximate. Generally, for matching human text, you'll want coll() which respects character matching rules for the specified locale." - camille