Concatenate previous and latter words to a word that match a condition in R

Viewed 125

I need to concatenate the previous and the latter words of a condition meeting word. Specifically, those who match the condition of having a comma.

vector <- c("Paulsen", "Kehr,", "Diego",    "Schalper", "Sepúlveda,", "Diego")

#I know how to get which elements meet my condition:

grepl(",", vector)
#[1] FALSE  TRUE FALSE FALSE  TRUE FALSE 

Desired output:

print(vector_ok)
#[1] "Paulsen Kehr, Diego", "Schalper Sepúlveda, Diego"

Thanks in advance!

1 Answers

You can use grep() to get the positions of the strings with a comma, expand these to a sequence +/- 1, and use this to index and then collapse the original vector.

idx <- grep(",", vector)
seqs <- Map(`:`, idx-1, idx+1)
sapply(seqs, function(x) paste(vector[x], collapse = " "))

[1] "Paulsen Kehr, Diego"       "Schalper Sepúlveda, Diego"
Related