Suppose we have a data frame as below :
test<-data.frame(v1=c(1:10),v2=c(rep("a x",10)),v3=c(rep(c("a b","a c","a d","a e","a f"),2)),v4=c((rep("p",5)),rep("q",5)))
Basically, we need to replace "a" in the strings of columns 2 and 3 with the string mentioned in column 4. The result data frame should ideally look like this:
result<-data.frame(v1=c(1:10),v2=c(rep("p x",5),rep("q x",5)),v3=c("p b","p c","p d","p e","p f","q b","q c","q d","q e","q f"),v4=c((rep("p",5)),rep("q",5)))
Have tried the following to get the same:
for (i in 1:nrow(test))
{
test[i,2]<-gsub("a",test[i,4],test[,2])
test[i,3]<-gsub("a",test[i,4],test[,3])
}
Have also tried using apply functions, but wasn't able to achieve the desired result.
Any help in this regard would be highly appreciated. Thanks in advance!