将前后单词连接到与 R 中的条件匹配的单词
Concatenate previous and latter words to a word that match a condition in R
我需要连接满足条件的单词的前后单词。具体来说,那些符合逗号条件的人。
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
期望的输出:
print(vector_ok)
#[1] "Paulsen Kehr, Diego", "Schalper Sepúlveda, Diego"
提前致谢!
您可以使用 grep()
获取带逗号的字符串的位置,将这些扩展为序列 +/- 1,并使用它来索引然后折叠原始向量。
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"
我需要连接满足条件的单词的前后单词。具体来说,那些符合逗号条件的人。
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
期望的输出:
print(vector_ok)
#[1] "Paulsen Kehr, Diego", "Schalper Sepúlveda, Diego"
提前致谢!
您可以使用 grep()
获取带逗号的字符串的位置,将这些扩展为序列 +/- 1,并使用它来索引然后折叠原始向量。
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"