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

走远了吗. 提交于 2020-01-04 00:19:12

问题


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:


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"


来源:https://stackoverflow.com/questions/58551389/concatenate-previous-and-latter-words-to-a-word-that-match-a-condition-in-r

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!