0

I have a dataframe with a variable (list) where is it possible to find special symbols. Please find below and example or my dataframe:

 df_1 <- data.frame(id=1:6,
 path.vec = I(list("apple", "lemon", "melon",c("apple", "banana","melon"),
 c("(Tuesday)/lemon", "lemon_Tuesday", "grape/ginger_peppers"),
 c("apple", "lemon", "apple"))))
 Recombine the path

df_1$recombined = as.character(map(df_1$path.vec, paste, collapse = " > "))

what I want to do is just to find and replace exact matches in my df_1$recombined

I have been trying with gsub

df_1$recombined <- gsub("\<(Tuesday)/lemon\>", "Tuesday", df_1$recombined, fixed =T)

this looks like running but it's not replacing any value. I have been browsing around and I have found that gsub doens't work well with special characters, so I have tried to with backslashes

 df_1$recombined <- gsub("\<\(\Tuesday\)\/lemon\>", "Tuesday", df_1$recombined, fixed =T)

but it doesn't change anyhting as well as square brackets:

 df_1$recombined <- gsub("\<[(]Tuesday[)]/lemon\>", "Tuesday", df_1$recombined, fixed =T)

both are running smoothly but not changing any value.

Eventually I would like the below output:

final.recombined
apple
lemon
melon
apple > banana > melon
Tuesday > Tuesday > Grape
apple > lemon > apple

I think this is kind of easy but I can't understand what I'm doing wrong and since the special characters is gsub the best function to use in this situation? I will replace any string with special characters to get from 2 words just one.

thanks!

Christoph
  • 6,841
  • 4
  • 37
  • 89
vally
  • 21
  • 2

1 Answers1

0

thanks everyone I have solved with the below:

 gsub("\\(Tuesday\\)\\/lemon", "Tuesday", df_1$recombined)

using the double escape before any special character solved it. Can I consider this a general solution?

vally
  • 21
  • 2