0

I have a long text vector(a.v) and a short one (b.v). Some of b.v words exist in a.v- some only once and others can be few times, or not at all.

I want that all of the b.v words that exist in A.v will be replaced by “ed” . So the “new.a.v” will have the same number of words, but instead of words that were exist in b.v there will be “ed”.

I tried grep and replace solution variations, but with no success. If b.v includes only 1 word, I guess it was easier, but b.v include 70 words, do typing and replace each one separately is not a fun option.

What should I do? I have

 `x<- c( "dog", "cat", "cat", "bear", "dog", "fish", "sky", "table", "chair", "girl", "boy" ,"picture")
 pet.animal<- c( "dog", "cat", "fish" )
 house.things<- c("table" ,"chair", "picture")
 x<- str_replace_all(x,"dog", "pet") 
 x<- str_replace_all(x,"cat", "pet") 

The end product that I am looking for is :

x<- c( "pet", "pet", "pet", "bear", "pet", "pet", "sky", "house", "house", "girl", "boy" ,"house")

I could do

x<- c( "dog", "cat", "cat", "bear", "dog", "fish", "sky", "table", "chair", "girl", "boy" ,"picture")
pet.animal<- c( "dog", "cat", "fish" )
house.things<- c("table" ,"chair", "picture")
x<- str_replace_all(x,"dog", "pet") 
x<- str_replace_all(x,"cat", "pet") 

but than I need to replace each one … so I am looking for a way to use pet.animal as the “pattern” for the replace. Something that will look whether the first pet.animal is in x, replace it if exist, if not move to the second word in pet.animal and so on.

Just to make things more complicated, pet.animal and house.things are not the same length…

Gili
  • 1
  • 3
  • Read about [How to make a great R reproducible example?](http://stackoverflow.com/questions/5963269), and please add your code even if it didn't work. – zx8754 Feb 11 '16 at 20:09

1 Answers1

0

This works for both pet and house

 v<-gsub(paste(house.things, collapse='|'), 'house', gsub(paste(pet.animal, collapse='|'), 'pet', x))
>v
#[1] "pet"   "pet"   "pet"   "bear"  "pet"   "pet"   "sky"   "house" "house" "girl" 
#[11] "boy"   "house"
Sotos
  • 51,121
  • 6
  • 32
  • 66