Sebastian Zeki
Sebastian Zeki

Reputation: 6874

How to perform conditional search within a nested list

I have a nested list as follows:

list(c("Oesophagus irregular z-line as previously.", " quad biopsies at ,,,m"
), c("Normal examination", "cardia mild inflammation."
), c("stomach normal", "Small polyp EMR and completely removed", 
"Duodenum  normal", "Jejunum normal", "GOJ normal", 
"Nodule seen at the mid oesophagus normal", "This was removed by EMR", 
"All other sites normal  normal", " A small area of residual stomach was removed by APC "))

I would like to search in each element for the presence of any term taken from a list called EventList:

EventList<-c("RFA","EMR","APC")

If the term is found then I would like to see if a location from a locaation list, is also present in the same sentence:

LocationList<-function(){

  tofind <-paste(c("Stomach","Antrum","Duodenum","Oesophagus","GOJ"),collapse = "|")

  return(tofind)

}

If it is not found then I'd like to look in the preceding sentence to see if a location can be seen.

So far I have been able to look in the same sentence only:

r1 <-lapply(text,function(x) Map(paste, str_extract_all(tolower(x),tolower(EventList)), str_extract_all(tolower(x),tolower(LocationList())), MoreArgs = list(sep=":")))

but this just looks for the presence of the terms in each sentence and outputs nothing if not present. How do I convert this to also look in the preceding sentence in a list? Someting like this:

ifelse(lapply(text,function(x) str_extract_all(tolower(x),tolower(LocationList())),str_extract_all(tolower(x),tolower(EventList()), lag element and do the same??

Intended output:

1 ""
2 ""
3 stomach:EMR,oesophagus:EMR,stomach:APC

Upvotes: 2

Views: 77

Answers (1)

akrun
akrun

Reputation: 887511

Based on the conditions mentioned in the post

sapply(text,function(x) {

           x1 <- str_extract_all(tolower(x),tolower(paste(EventList, collapse="|")))
           i1 <- which(lengths(x1) > 0)
           if(any(i1)) {
             paste(unlist(Map(c, str_extract_all(tolower(x[i1-1]), 
                                         tolower(LocationList())), 
                       str_extract_all(tolower(x[i1]), tolower(LocationList())))), 
                        toupper(x1[i1]), sep=":", collapse=", ") 

           } else ""

             }

             )

#[1] ""  
#[2] ""   
#[3] "stomach:EMR, oesophagus:EMR, stomach:APC"

Upvotes: 1

Related Questions