Как удалить куски текста * разной длины * из разных текстов в символьном векторе? - PullRequest
1 голос
/ 16 октября 2019

У меня есть символьный вектор, содержащий 231 документ (231 строка на один столбец). В начале каждого документа есть фрагмент текста, который я хотел бы удалить из каждого из 231 документа. Проблема в том, что длина этого фрагмента варьируется от документа к документу.

Давайте рассмотрим пример, где каждый текст имеет следующее начало: Текст, который я хочу удалить .:

Я попробовал следующие варианты безрезультатно:

x <- c("Text that I wish to remove because I don't like it. I really want to remove the text but I cannot do it. I hope that stackoverflow will sort it out.", 
  "Text that I wish to remove. I really want to remove the text but I cannot do it. I hope that stackoverflow will sort it out.", 
  "Text that I wish to remove and I will remove it because some great data analyst will help me solve it. I really want to remove the text but I cannot do it. I hope that stackoverflow will sort it out.", 
  "Text that I wish to remove and who know whether I manage to make it work, it could be and it could not be. I really want to remove the text but I cannot do it. I hope that stackoverflow will sort it out.")

Если бы удаляемый кусок был равным, я бы просто сделал следующее, как мне предлагали в предыдущем посте:

strings <- substring(x, 60)

Тем не менее, я застрял, потому что длина отличается для любого текста.

В идеале, я хотел бы получить:

[1] "I really want to remove the text but I cannot do it. I hope that stackoverflow will sort it out."
[2] "I really want to remove the text but I cannot do it. I hope that stackoverflow will sort it out."
[3] "I really want to remove the text but I cannot do it. I hope that stackoverflow will sort it out."
[4] "I really want to remove the text but I cannot do it. I hope that stackoverflow will sort it out."

Может кто-нибудь помочь мне?

Большое спасибо!

Ответы [ 2 ]

2 голосов
/ 16 октября 2019

Вы можете использовать следующий код

  gsub("^.+\\. ", "", x)

[1] "I hope that stackoverflow will sort it out."
[2] "I hope that stackoverflow will sort it out."
[3] "I hope that stackoverflow will sort it out."
[4] "I hope that stackoverflow will sort it out."
1 голос
/ 16 октября 2019

Разделите на " ,", затем получите последнее предложение:

sapply(strsplit(x, ". ", fixed = TRUE), tail, n = 1)
# [1] "I hope that stackoverflow will sort it out."
# [2] "I hope that stackoverflow will sort it out."
# [3] "I hope that stackoverflow will sort it out."
# [4] "I hope that stackoverflow will sort it out."
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...