2

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!

2 Answers 2

1

We can loop over the columns, remove the 'a' and paste with the 'v4'

test[2:3] <- lapply(test[2:3], function(x) paste0(test$v4, sub("a", "", x)))
Sign up to request clarification or add additional context in comments.

Comments

1

Perhaps this? (not sure how generic you need the code to be)

test2 <- test
test2$v2 <- mapply(gsub ,  "a" , test$v4 , test$v2)
test2$v3 <- mapply(gsub ,  "a" , test$v4 , test$v3)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.