Попробуйте map
из purrr
(вы также можете просто загрузить tidyverse
):
library(tidyverse)
df %>%
mutate(
DiagnosisCode = map(
FindingsAfterProcessing, ~ case_when(
any(grepl("mitotic", tolower(.x))) ~ "C159",
any(grepl("emr", tolower(.x))) ~ "EMR",
TRUE ~ "other")
),
FindingsAfterProcessing = map(
FindingsAfterProcessing, ~ .x[!grepl("mitotic|emr", tolower(.x))]
)
)
Вывод здесь будет:
FindingsAfterProcessing DiagnosisCode
1 Normal Mucosa Throughout other
2 C159
3 Normal other
4 Hiatus Hernia C159
5 Normal Mucosa Throughout other
6 HALO RFA to Barrett's oesophagus other
7 Barretts oesophagus other
8 Barrett's oesophagus EMR
Это не 100% соответствуют вашему желаемому выводу, но я предполагаю, что в вашем выводе есть опечатка?
Я говорю это, потому что мой вывод основан на списке, который вы предоставили;Я превратил его в столбец данных:
df <- data.frame(FindingsAfterProcessing = I(list( "Normal Mucosa Throughout", "Mitotic Lesion- See Text Above",
"Normal",
c("Mitotic", "Hiatus Hernia"), "Normal Mucosa Throughout",
"HALO RFA to Barrett's oesophagus", "Barretts oesophagus",
c("Barrett's oesophagus ", "EMR"))))