I want to replace each 'COL' word in the column 'b' of the 'test' data frame, by each element in the column 'a', and put the result in other column, but preserving both order and structure of the character string of the column 'b'.
test <- data.frame(a = c("COL167", "COL2010;COL2012"),
b = c("COL;MO, K", "P;COL, NY, S, COL"))
I have tried the following, but it is not the result that I need:
for(i in 1:length(test$a)){
test$c[i] <- gsub(pattern = "COL", x = test$b[i], replacement = test$a[i])
}
> test
a b c
1 COL167 COL;MO, K COL167;MO, K
2 COL2010;COL2012 P;COL, NY, S, COL P;COL2010;COL2012, NY, S, COL2010;COL2012
I expect the following result:
a b c
1 COL167 COL;MO, K COL167;MO, K
2 COL2010;COL2012 P;COL, NY, S, COL P;COL2010, NY, S, COL2012