0

If I have a dataframe was values such as:

df<- c("One", "Two Three", "Four", "Five")
df<-data.frame(df)

df
"One"
"Two Three"
"Four"
"Five"

And I have another dataframe such as:

df2<-c("the park was number one", "I think the park was number two three", "Nah one and two is ok", "tell me about four and five")
df2<-data.frame(df2)

df2
the park was number one
I think the park was number two three
Nah one and two is ok
tell me about four and five

If one of the values found in df are found in any of the strings of df2[,1], how do I replace it with a word like "it".

I want to replace my final df2 with this:

df3
the park was number it
I think the park was number it
Nah it and two is ok
tell me about it and it

I know it probably has to do with something like:

gsub(df,"it", df2)

But I don't think that is right.

Thanks!

nak5120
  • 4,089
  • 4
  • 35
  • 94
  • 2
    I think you have been around enough to know that you need to provide a [reproducible example](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) rather than copy/pasting your data. – M-- Aug 17 '17 at 19:54
  • Sorry just edited the question – nak5120 Aug 17 '17 at 20:00

1 Answers1

1

You could do something like

sapply(df$df,function(w) df2$df2 <<- gsub(paste0(w,"|",tolower(w)),"it",df2$df2))

df2 
                             df2
1         the park was number it
2 I think the park was number it
3           Nah it and two is ok
4        tell me about it and it

The <<- operator makes sure that the version of df2 in the global environment is changed by the function. The paste0(w,"|",tolower(w)) allows for differences of capitalisation, as in your example.

Note that you should add stringAsFactors=FALSE to your dataframe definitions in the question.

Andrew Gustar
  • 17,295
  • 1
  • 22
  • 32