Reputation: 745
Hi I have this data frame (DF1)
structure(list(Value = list("Peter", "John", c("Patric", "Harry")),Text = c("Hello Peter How are you","Is it John? Yes It is John, Harry","Hello Patric, how are you. Well, Harry thank you.")) , class = "data.frame", row.names = c(NA, -3L))
Value Text
1 Peter Hello Peter How are you
2 John Is it John? Yes It is John, Harry
3 c(Patric, Harry) Hello Patric, how are you. Well, Harry thank you.
And I would like to split sentences in Text by names in Value to have this
Value Text Split
1 Peter Hello Peter How are you c("Hello", "Peter How are you")
2 John Is it John? Yes It is John, Harry c("Is it", "John? Yes It is John, Harry")
3 c(Patric, Harry) Hello Patric, how are you. Well, Harry thank you c("Hello", "Patric, how are you. Well,", "Harry thank you")
I tried this
DF1 %>% mutate(Split = strsplit(as.character(Text),as.character(Value)))
But it does not work
Upvotes: 0
Views: 162
Reputation: 7818
Assuming this is the real structure:
df <- structure(list(Value = list("Peter", "John", c("Patric", "Harry")),
Text = c("Hello Peter How are you","Is it John? Yes It is John, Harry","Hello Patric, how are you. Well, Harry thank you.")),
class = "data.frame", row.names = c(NA, -3L))
You can solve your problem with a double for loop. This is probably a more readable solution and easier to debug.
library(stringr)
Split <- list()
for(i in seq_len(nrow(df))){
text <- df$Text[i]
value <- df$Value[[i]]
for(j in seq_along(value)){
text2 <- str_split(text[length(text)], paste0("(?<=.)(?=", value[[j]], ")"), n = 2)[[1]]
text <- c(text[-length(text)], text2)
}
Split[[i]] <- text
}
df$Split <- Split
If you print df
it will look like you have one unique string, but it is not.
df$Split
#> [[1]]
#> [1] "Hello " "Peter How are you"
#>
#> [[2]]
#> [1] "Is it " "John? Yes It is John, Harry"
#>
#> [[3]]
#> [1] "Hello " "Patric, how are you. Well, " "Harry thank you."
#>
Since in your initial attempt you were using dplyr
functions, you can also write it this way with a recursive function. This solution uses no for loops.
library(stringr)
library(purrr)
library(dplyr)
str_split_recursive <- function(string, pattern){
string <- str_split(string[length(string)], paste0("(?<=.)(?=", pattern[1], ")"), n = 2)[[1]]
pattern <- pattern[-1]
if(length(pattern) > 0) string <- c(string[-length(string)], str_split_recursive(string, pattern))
string
}
df <- df %>%
mutate(Split = map2(Text, Value, str_split_recursive))
Upvotes: 1