0

here is the example data:

example_sentences <- data.frame(doc_id = c(1,2,3),
                                sentence_id = c(1,2,3),
                                sentence = c("problem not fixed","i like your service and would tell others","peope are nice however the product is rubbish"))
matching_df <- data.frame(x = c("not","and","however"))

Created on 2019-01-07 by the reprex package (v0.2.1)

I want to add/insert a comma just before a certain word in a character string. for example if my string is:

problem not fixed.

I want to convert this to

problem, not fixed.

The other matching_df contains the words to match (these are Coordinate conjunctions) so if the x is found in matching_df then insert comma + space before the detected word.

I have looked at stringr package but not sure how to achieve this.

Best,

1
  • @MrFlick I edited with the reprex example
    – Shery
    Jan 7, 2019 at 17:37

2 Answers 2

Reset to default

Trending sort

Trending sort is based off of the default sorting method — by highest score — but it boosts votes that have happened recently, helping to surface more up-to-date answers.

It falls back to sorting by highest score if no posts are trending.

2

The gsubfn function in the gsubfn package takes a regular expression as the first argument and a list (or certain other objects) as the second argument where the names of the list are strings to be matched and the values in the list are the replacement strings.

library(gsubfn)

gsubfn("\\w+", as.list(setNames(paste0(matching_df$x, ","), matching_df$x)), 
  format(example_sentences$sentence))

giving:

[1] "problem not, fixed                            "
[2] "i like your service and, would tell others    "
[3] "peope are nice however, the product is rubbish"
1
  • this is sick!! will give it a go today
    – Shery
    Jan 8, 2019 at 9:54
1

I've no idea what the data frame you're talking about looks like, but I made a simple data frame containing some phrases here:

df <- data.frame(strings = c("problems not fixed.","Help how are you"),stringsAsFactors = FALSE)

I then made a vector of words to put a comma after:

words <- c("problems","no","whereas","however","but")

Then I put the data frame of phrases through a simple for loop, using gsub to substitute the word for a word + comma:

for (i in 1:length(df$strings)) {
    string <- df$strings[i]
    findWords <- intersect(unlist(strsplit(string," ")),words)
    if (!is.null(findWords)) {
        for (j in findWords) {
            df$strings[i] <- gsub(j,paste0(j,","),string)
        }
    }
}

Output:

 df
               strings
1 problems, not fixed.
2     Help how are you
1
  • I edited the question but your solution looks good. thanks for your help
    – Shery
    Jan 7, 2019 at 17:45

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.