co = getPubMed("../tmData/pubmed-postpartum-set.txt") %>% DFSource %>% VCorpus

co
## <<VCorpus>>
## Metadata:  corpus specific: 0, document level (indexed): 0
## Content:  documents: 101
length(co) # 101 documents 
## [1] 101
# Create tdm
tdm = as.matrix(TermDocumentMatrix(co))

# Show the metadata for the first 5 documents in your corpus.
lapply(co,meta) %>% head(5)
## $`32683141`
##   author       : Young LJ
##   datetimestamp: 2020-07-20
##   description  : character(0)
##   heading      : character(0)
##   id           : 32683141
##   language     : en
##   origin       : character(0)
##   PMID         : 32683141
##   title        : Oxytocin and postpartum depression: A systematic review.
## 
## $`33958824`
##   author       : Say L
##   datetimestamp: 2021-05-08
##   description  : character(0)
##   heading      : character(0)
##   id           : 33958824
##   language     : en
##   origin       : character(0)
##   PMID         : 33958824
##   title        : Mental health of adolescents associated with sexual and reproductive outcomes: a  systematic review.
## 
## $`33950611`
##   author       : Gaynes BN
##   datetimestamp: 2021-04-01
##   description  : character(0)
##   heading      : character(0)
##   id           : 33950611
##   language     : en
##   origin       : character(0)
##   PMID         : 33950611
##   title        : Maternal, Fetal, and Child Outcomes of Mental Health Treatments in Women: A  Systematic Review of Perinatal Pharmacologic Interventions
## 
## $`35780969`
##   author       : Alderdice F
##   datetimestamp: 2022-07-06
##   description  : character(0)
##   heading      : character(0)
##   id           : 35780969
##   language     : en
##   origin       : character(0)
##   PMID         : 35780969
##   title        : How women with obsessive compulsive disorder experience maternity care and mental  health care during pregnancy and postpartum: A systematic literature review.
## 
## $`33811827`
##   author       : Khalil A
##   datetimestamp: 2021-04-04
##   description  : character(0)
##   heading      : character(0)
##   id           : 33811827
##   language     : en
##   origin       : character(0)
##   PMID         : 33811827
##   title        : Effects of the COVID-19 pandemic on maternal and perinatal outcomes: a systematic  review and meta-analysis.
# Show the titles for the first 5 documents in your corpus
meta(co,"title") %>% head(5)
## $`32683141`
##                                                       title
## 1: Oxytocin and postpartum depression: A systematic review.
## 
## $`33958824`
##                                                                                                   title
## 1: Mental health of adolescents associated with sexual and reproductive outcomes: a  systematic review.
## 
## $`33950611`
##                                                                                                                                      title
## 1: Maternal, Fetal, and Child Outcomes of Mental Health Treatments in Women: A  Systematic Review of Perinatal Pharmacologic Interventions
## 
## $`35780969`
##                                                                                                                                                              title
## 1: How women with obsessive compulsive disorder experience maternity care and mental  health care during pregnancy and postpartum: A systematic literature review.
## 
## $`33811827`
##                                                                                                           title
## 1: Effects of the COVID-19 pandemic on maternal and perinatal outcomes: a systematic  review and meta-analysis.
################################################################################

# First make all words lowercase, then remove: punctuation, stop words, numbers, 
# and only show words that appear more than 3 times in a document, and in more 
# than 3 documents 
tdm1 = as.matrix(TermDocumentMatrix(co, control=list(tolower = TRUE,
                                                     removePunctuation=T, 
                                                     stopwords=T,
                                                     removeNumbers=T,
                                                     bounds=list(local=c(3,Inf),
                                                                 global=c(3,Inf)))))

# Create a wordcloud
sums1 = rowSums(tdm1)

# Clean up the names in sums1
names(sums1) = gsub("[^[:alnum:] ]", "", names(sums1))

set.seed(101L)
length(unique(sums1))
## [1] 49
set.seed(101L)
wordcloud(names(sums1),sums1,min.freq=1,scale=c(3.5,.3),colors=c(1:length(unique(sums1))))

################################################################################

# Get words that appear in at least 50% of the documents at least once:
tdm2 = as.matrix(TermDocumentMatrix(co, control=list(tolower = TRUE,
                                                     removePunctuation=T, 
                                                     stopwords=T,
                                                     removeNumbers=T,
                                                     bounds=list(global=c(length(co)
                                                                        *0.5,Inf)))))

# Create a wordcloud
sums2 = rowSums(tdm2)
set.seed(101L)
length(unique(sums2))
## [1] 15
set.seed(101L)
wordcloud(names(sums2),sums2,min.freq=1,scale=c(3.5,.3),colors=c(1:length(unique(sums2))))

################################################################################

# Lets add onto the connections we see with the words "ppd" and "depression" 
# with our topic, postpartum:

# number of times the word "ppd" & "depression" appears in all the documents

tdm3 = TermDocumentMatrix(co, control=list(tolower=TRUE, removePunctuation=T))

# ppd
(ppd_count = sum(tdm3["ppd", ]))     # 100
## [1] 100
# depression
(depression_count = sum(tdm3["depression", ]))    # 288
## [1] 288
#####################

# find all words that appear in at least one document
freq_terms = findFreqTerms(tdm3, lowfreq=1)

# number of documents "ppd" appears in 
ppd = tdm3["ppd", ]
sum(ppd > 0)            # 17
## [1] 17
# number of documents "depression" appears in 
depression = tdm3["depression", ]
sum(depression > 0)     # 68
## [1] 68
################################################################################

# Extract the datetimestamp metadata field for all documents in the corpus
dates = meta(co, "datetimestamp")

# Convert list of dates to a vector
dates_vec = unlist(dates)

# Find the oldest and newest document dates
(oldest_date = min(dates_vec)) # "2019-07-16"
## [1] "2019-07-16"
(newest_date = max(dates_vec)) # "2023-04-29"
## [1] "2023-04-29"
################################################################################


# Since the documents date time samp is from 7/2019 to 4/2023, lets analyze the
# role of covid in this topic/documents: 

# number of times the word covid-19 & coronavirus appears in all the documents

# covid19
(covid19_count = sum(tdm3["covid19", ]))     # 48
## [1] 48
# coronavirus
(coronavirus_count = sum(tdm3["coronavirus", ]))    # 4
## [1] 4
#####################

# number of documents "covid19" appears in 
covid19 = tdm3["covid19", ]
sum(covid19 > 0)              # 12 
## [1] 12
# number of documents "coronavirus" appears in
coronavirus = tdm3["coronavirus", ]
sum(coronavirus > 0)          # 4
## [1] 4
################################################################################

tdm4 = as.matrix(TermDocumentMatrix(co, control=list(tolower = TRUE,
                                                     removePunctuation=T)))

sums = rowSums(tdm4)

# Create a data table for your term-document frequency.
dt1 = data.table(word = names(sums), freq = sums)

####################

# BING / NEGATIVE

dt2 = data.table(get_sentiments("bing"))

# Select all the negative words using the bing lexicon
dtneg = dt2[dt1,on=.(word),nomatch=NULL][sentiment=='negative']
dtneg[,sentiment:=NULL]

# Wordcloud
wordcloud2(dtneg, size=1)
####################

# BING / POSITIVE

# Select all the positive words using the bing lexicon
dtpos = dt2[dt1,on=.(word),nomatch=NULL][sentiment=='positive']
dtpos[,sentiment:=NULL]

# Word cloud
wordcloud2(dtpos, size=1)
###################

# NRC / NEGATIVE

# Get the nrc lexicon as a data table
nrc = as.data.table(get_sentiments("nrc"))

# Select all the negative words using the nrc lexicon
nrc_neg = dt1[nrc, on = .(word), nomatch = NULL][sentiment == 'negative']

# Convert nrc_neg to a data frame
nrc_neg_df = as.data.frame(nrc_neg)

# Generate a wordcloud using wordcloud2
wordcloud2(nrc_neg_df, size = 0.3)
###################

# NRC / FEAR

# Select all the fear words using the nrc lexicon
nrc_fear = dt1[nrc,on = .(word),nomatch = NULL][sentiment == 'fear']

# Convert nrc_neg to a data frame
nrc_fear_df = as.data.frame(nrc_fear)

# Generate a wordcloud using wordcloud2
wordcloud2(nrc_fear_df, size = 0.3)
################################################################################

# Phrase docs

pd=phraseDoc(co)
## [1] "2023-11-14 23:51:10 EST"
## [1] "2023-11-14 23:51:11 EST"
## [1] "Rectifying frequencies..."
## [1] "2023-11-14 23:51:17 EST"
pdm=as.matrix(pd)

# Show the 10 most frequent principal phrases in the corpus.
freqPhrases(pd,10L)
##                         frequency
## 95% ci                        100
## postpartum depression          53
## mental health                  37
## systematic review              27
## risk factors                   26
## pregnant women                 25
## web of science                 24
## depressive symptoms            23
## 95% confidence interval        22
## systematic reviews             20
# Find the document that has the highest frequency of the phrase “postpartum depression”. 
getDocs(pd,"postpartum depression", F)   
##                       1 3 7 10 11 18 24 25 29 30 35 38 39 41 44 50 53 56 59 61
## postpartum depression 3 1 1  1  6  1  4  1  5  1  1  1  1  2  4  3  1  1  1  3
##                       72 83 85 90 95
## postpartum depression  5  2  2  1  1
sort(getDocs(pd,"postpartum depression",F))
##  [1] 1 1 1 1 1 1 1 1 1 1 1 1 1 1 2 2 2 3 3 3 4 4 5 5 6
# document 11 has postpartum depression 6 times

# Get title of that document
meta(co,"title")[11]
## $`33360589`
##                                                                                                                                                                                                                             title
## 1: The effectiveness of telemedicine interventions, delivered exclusively during the  postnatal period, on postpartum depression in mothers without history or existing  mental disorders: A systematic review and meta-analysis.
# Inspect that document to see if you can find the phrase(s). 
inspect(co[[11]])
## <<PlainTextDocument>>
## Metadata:  9
## Content:  chars: 2210
## 
## BACKGROUND: Postpartum depression, one of the most common forms of depression, is  highly prevalent worldwide among women during childbirth. Despite available  treatments for postpartum depression, numerous barriers hinder women to access  care including time, financial constraints, and childcare concerns. Telemedicine  interventions are suggested to be feasible to prevent and improve postpartum  depression. OBJECTIVE: To examine the effectiveness of telemedicine interventions  - delivered exclusively during the postnatal period, on postpartum depression  symptomatology in women with no history of mental disorders. DESIGN: A systematic  review and meta-analysis of randomized controlled trials. METHODS: PubMed, Web of  Science, Cochrane Library, and ProQuest Dissertations & Theses databases were  used to identify relevant randomized controlled trials, until 7 January 2020.  Studies were quality assessed using the Cochrane Library Risk of Bias Tool. The  results of postpartum depression scores were pooled using a random-effects model.  Intervention completion rate and participants' satisfaction were reported in a  narrative form, as secondary outcomes. RESULTS: Ten trials including a total of  2366 participants, contributed data to the review. Seven studies were included in  the quantitative synthesis. Women who received technology-based interventions,  regardless of the type (web-based versus telephone-based), had a statistically  significant improvement in postpartum depression (mean difference: -1.81, 95% CI:  -2.68 to -0.93; P<.0001). The completion rate was 80% in the intervention groups  compared to 76% in the control groups. Three studies reporting participants'  satisfaction revealed that the participants were highly satisfied with the  technology-based interventions. CONCLUSION: Overall, telemedicine interventions  appear to be promising in preventing and improving postpartum depression. Further  larger-scale high-quality research is required to establish an evidence-based  telemedicine approach, in terms of structure, content, and providers. Future  economic evaluation is also vital to evaluate the long-term use of telemedicine  in improving postpartum depression.
# Find the full set of principal phrases for document 11
(gp=getPhrases(pd,11))
##                                     33360589
## 95% ci                                     1
## among women                                1
## assessed using the cochrane                1
## cochrane library                           1
## completion rate                            2
## control groups                             1
## highly prevalent                           1
## improving postpartum depression            2
## january 2020                               1
## mean difference                            1
## mental disorders                           1
## one of the most common                     1
## postnatal period                           1
## postpartum depression                      6
## proquest dissertations                     1
## randomized controlled trials               2
## research is required                       1
## risk of bias tool                          1
## statistically significant                  1
## studies reporting                          1
## studies were included                      1
## systematic review and meta-analysis        1
## technology-based interventions             2
## telemedicine interventions                 3
## used to identify                           1
## using a random-effects model               1
## web of science                             1
## women who received                         1
# Create a word cloud for all principal phrases in the document 
dt=data.table(word=rownames(gp),freq=gp[,1])
wordcloud2(dt,size=0.2)
######################

# do the same thing but for the document with the second highest frequency 

# Find the document that has the SECOND highest frequency of the phrase 
# “postpartum depression”. 
getDocs(pd,"postpartum depression",F)   
##                       1 3 7 10 11 18 24 25 29 30 35 38 39 41 44 50 53 56 59 61
## postpartum depression 3 1 1  1  6  1  4  1  5  1  1  1  1  2  4  3  1  1  1  3
##                       72 83 85 90 95
## postpartum depression  5  2  2  1  1
sort(getDocs(pd,"postpartum depression",F))
##  [1] 1 1 1 1 1 1 1 1 1 1 1 1 1 1 2 2 2 3 3 3 4 4 5 5 6
# documents 29 & 72 both have postpartum depression 5 times
# lets analyze document 29

# Get title of both documents
meta(co,"title")[29]
## $`32974057`
##                                                                                                                             title
## 1: Postpartum depression and associated factors among postpartum women in Ethiopia:  a systematic review and meta-analysis, 2020.
# Inspect that document to see if you can find the phrase(s). 
inspect(co[[29]])
## <<PlainTextDocument>>
## Metadata:  9
## Content:  chars: 2255
## 
## INTRODUCTION: The postpartum period is recognized as a high-risk period for the  development of various mood disorders like postpartum depression. Globally,  postnatal depression is a serious public health problem that has a negative  impact on the mother's health and child development, especially in developing  countries. In Ethiopia, even though there are different primary studies conducted  on postpartum depression, there is no nationally representative evidence.  Therefore, the aim of this systematic review and meta-analysis was to estimate  the pooled prevalence and associated factors of postpartum depression in  Ethiopia. METHODS: Published and unpublished articles from various electronic  databases and digital libraries were accessed. This systematic review included  studies that were conducted on the magnitude and factors associated with  postpartum depression among postnatal women in Ethiopia. A random-effect model  was used to estimate the pooled magnitude of postpartum depression with a 95%  confidence interval (CI). Inverse variance (I(2)) was used to visualize the  presence of heterogeneity, and forest plot was used to estimate the pooled  magnitude of postpartum depression. Publication bias was assessed by funnel plots  and Egger's statistical tests. A meta-regression and subgroup analysis were  computed to minimize underlying heterogeneity. RESULT: Initially, a total of 764  studies were accessed. Twenty-eight full articles were assessed for eligibility  criteria, of which twelve studies fulfilled inclusion criteria were included in  the final meta-analysis. The overall pooled magnitude of postpartum depression  was 22.89% (95% CI 17.75%, 28.03%) with the lowest (12.20%) and highest (33.82%)  in the Southern nations region. Unplanned pregnancy, domestic violence, lack of  social support, previous history of depression, infant loss, and dissatisfaction  in marriage showed a statistically significant association with postpartum  depression. CONCLUSIONS: In the current analysis, the prevalence of postpartum  depression was high as compared with other developing countries. Routine  screening of mothers in the postpartum period and integrating mental health with  maternal health care is highly recommended.
# Find the full set of principal phrases for document 11
(gp2=getPhrases(pd,29))
##                                                     32974057
## 95% ci                                                     1
## 95% confidence interval                                    1
## aim of this systematic review                              1
## articles were assessed for eligibility                     1
## associated factors                                         1
## depression among                                           1
## domestic violence                                          1
## electronic databases                                       1
## especially in developing countries                         1
## estimate the pooled prevalence                             1
## factors associated with postpartum                         1
## funnel plots and egger                                     1
## health care                                                1
## history of depression                                      1
## included in the final                                      1
## inclusion criteria                                         1
## mental health                                              1
## mood disorders                                             1
## overall pooled                                             1
## postnatal depression                                       1
## postnatal women                                            1
## postpartum depression                                      5
## postpartum period                                          2
## prevalence of postpartum depression                        1
## primary studies                                            1
## public health problem                                      1
## publication bias was assessed                              1
## random-effect model                                        1
## showed a statistically significant                         1
## social support                                             1
## studies that were conducted                                1
## subgroup analysis                                          1
## systematic review                                          1
## twelve studies                                             1
## unplanned pregnancy                                        1
## used to estimate the pooled magnitude of postpartum        2
# Create a word cloud for all principal phrases in the document 
dt2=data.table(word=rownames(gp2),freq=gp2[,1])
wordcloud2(dt2, size = 0.1)