Заменить общие выражения во фрейме данных - PullRequest
1 голос
/ 14 апреля 2020

У меня есть фрейм данных из текстов, взятых из Википедии. Примером может быть:

dput(text3)
structure(list(texts = c("Apollo 13 was the seventh crewed mission in the Apollo space program and the third meant to land on the Moon. The craft was launched from Kennedy Space Center on April 11, 1970, but the lunar landing was aborted after an oxygen tank in the service module (SM) failed two days into the mission. The crew instead looped around the Moon, and returned safely to Earth on April 17. The mission was commanded by Lovell with Swigert as command module (CM) pilot and Haise as lunar module (LM) pilot. Swigert was a late replacement for Mattingly, who was grounded after exposure to rubella.", 
"A routine stir of an oxygen tank ignited damaged wire insulation inside it, causing an explosion that vented the contents of both of the SM's oxygen tanks to space. Without oxygen, needed for breathing and for generating electric power, the SM's propulsion and life support systems could not operate. The CM's systems had to be shut down to conserve its remaining resources for reentry, forcing the crew to transfer to the LM as a lifeboat. With the lunar landing canceled, mission controllers worked to bring the crew home alive. ", 
"Although the LM was designed to support two men on the lunar surface for two days, Mission Control in Houston improvised new procedures so it could support three men for four days. The crew experienced great hardship caused by limited power, a chilly and wet cabin and a shortage of potable water. There was a critical need to adapt the CM's cartridges for the carbon dioxide removal system to work in the LM; the crew and mission controllers were successful in improvising a solution. The astronauts' peril briefly renewed interest in the Apollo program; tens of millions watched the splashdown in the South Pacific Ocean on television."
), paragraph = c("p1", "p2", "p3"), source = c("wiki", "wiki", 
"wiki"), autronauts = c("Lovell", "Swigert", "Haise")), row.names = c(NA, 
-3L), class = "data.frame")

В моем исследовании мне нужно изучить людей в статьях по их социальной роли, реальные имена меня не интересуют. Поэтому мне нужно заменить каждое имя уникальным социальным индикатором.

Lovell = @ Astronaut1

Swigert = @ Austronaut2

Haise = @ Autronaut3

Mattingly = @ Austronaut4

a01 <- c('Lovell', 'Swigert', 'Haise' ,'Mattingly')
a02 <- c('@Astronaut1', '@Austronaut2', '@Autronaut3', '@Austronaut4')

С Я должен заменить строку в двух столбцах и сохранить формат фрейма данных, попробовал и потерпел неудачу:

library(stringi)
text3$texts <-  stri_replace_all_fixed(str = text3$texts, pattern = a01, replacement = a02)
Error in `$<-.data.frame`(`*tmp*`, texts, value = c("Apollo 13 was the seventh crewed mission in the Apollo space program and the third meant to land on the Moon. The craft was launched from Kennedy Space Center on April 11, 1970, but the lunar landing was aborted after an oxygen tank in the service module (SM) failed two days into the mission. The crew instead looped around the Moon, and returned safely to Earth on April 17. The mission was commanded by @Astronaut1 with Swigert as command module (CM) pilot and Haise as lunar module (LM) pilot. Swigert was a late replacement for Mattingly, who was grounded after exposure to rubella.",  : 
  replacement has 4 rows, data has 3
In addition: Warning message:
In stri_replace_all_fixed(str = text3$texts, pattern = a01, replacement = a02) :
  longer object length is not a multiple of shorter object length

и

text3$astronauts <-  stri_replace_all_fixed(str = text3$astronauts, pattern = a01, replacement = a02)
Error in `$<-.data.frame`(`*tmp*`, astronauts, value = c("@Astronaut1",  : 
  replacement has 4 rows, data has 3
In addition: Warning message:
In stri_replace_all_fixed(str = text3$astronauts, pattern = a01,  :
  longer object length is not a multiple of shorter object length

Любая помощь будет прекрасна

Ответы [ 3 ]

1 голос
/ 14 апреля 2020

Ошибка, полученная с:

stri_replace_all_fixed(str = text3$texts, pattern = a01, replacement = a02)

, основана на векторизованном подходе (по умолчанию). См. ?stringi-arguments:

Почти все функции векторизованы относительно всех своих аргументов, и правило повторного использования применяется при необходимости. Благодаря этому свойству вы можете, например, искать один шаблон в каждой заданной строке, искать каждый шаблон в одной заданной строке и искать i-й шаблон в i-й строке. Такое поведение иногда приводит к странным результатам - мы предполагаем, что вы знаете, что вы делаете.

В результате результатом будут 4 строковых объекта:

[1] первая строка в texts заменить первым шаблоном / заменой (Astronaut1)

[2] второй ряд в texts заменить вторым шаблоном / заменой (Astronaut2)

[3] третий ряд в texts заменить третьим шаблоном / заменой (Astronaut3)

[4] в первом ряду texts (переработано) заменить четвертым шаблоном / заменой (Astronaut4)

И после возврата объекта длины 4, это больше, чем 3 строки, которые вы пытаетесь заменить, которые вы начали в text3$texts, вызывая ошибку.

Чтобы обойти это, установите vectorize_all = FALSE:

stri_replace_all_fixed(str = text3$texts, pattern = a01, replacement = a02, vectorize_all = FALSE)

Который должен вернуть 3 строки и заменить все замены, следуя всем шаблонам в каждой из 3 строк.

1 голос
/ 14 апреля 2020

Вы можете попробовать следующее, используя stringr::str_replace_all:

library(stringr)

text3$texts <- str_replace_all(text3$texts, c("Lovell" = "@Astronaut1", 
"Swigert" = "@Astronaut2", "Haise" = "@Astronaut3", "Mattingly" = "@Astronaut4"))

text3


texts
1                                       Apollo 13 was the seventh crewed 
mission in the Apollo space program and the third meant to land on the Moon. 
The craft was launched from Kennedy Space Center on April 11, 1970, but the 
lunar landing was aborted after an oxygen tank in the service module (SM) 
failed two days into the mission. The crew instead looped around the Moon, 
and returned safely to Earth on April 17. The mission was commanded by 
@Astronaut1 with...
0 голосов
/ 14 апреля 2020

это должно работать в Base R

for(X in 1:length(a01)){
  text3 <- gsub(a01[X],a02[X],text3)
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...