setwd("~/Dropbox/Marie Curie/postdoc/manuscript in prep/frontiers in conservation and the media")
library(maps)
library(tidyverse)
library(cowplot)
library(export)
library(dplyr)
library(likert)
library(HH)
library(sjPlot)
library(svglite)
library(nnet)
library(tidyr)
library(export)
library(tidytext)
library(wordcloud)
library(readr)
library(tidyverse)
library(lme4)
library(wordcloud2)

### Figure 1

scores <- read.csv("country_code_110523.csv", header = T)
str(scores)

View(scores)

world_map <- map_data("world")
gg1 <- ggplot(scores) + 
  geom_map(dat=world_map, map=world_map, 
           aes(map_id=region), fill="white", color="lightgrey") + 
  geom_map(map=world_map, 
          aes(map_id=Country, fill=bee), color="black") +
  scale_fill_distiller(palette="PuBu", direction=1)+
  expand_limits(x = world_map$long, y = world_map$lat)+
  ylim(-52,78)+
  xlim(-165,175)+
  xlab("Long") +
  ylab("Lat")+
  theme_bw()
gg1

ggsave(file="map_bee1.svg", plot=gg1, width=6, height=4)

gg2 <- ggplot(scores) + 
  geom_map(dat=world_map, map=world_map, 
           aes(map_id=region), fill="white", color="lightgrey") + 
  geom_map(map=world_map, 
           aes(map_id=Country, fill=wasp), color="black") + 
  expand_limits(x = world_map$long, y = world_map$lat)+
  scale_fill_distiller(palette="Reds", direction =1)+
  ylim(-52,78)+
  xlim(-165,175)+
  xlab("Long") +
  ylab("Lat")+
  theme_bw()
gg2

grid.arrange(gg1, gg2, nrow = 2)
#graph2doc(file="map_wasp_bee.docx",width=6, height=7)


chisq.test(scores$bee, scores$wasp, correct=FALSE)
fisher.test(scores$bee, scores$wasp)

##### Continent plot Fig S1

data <- read.csv("data_survey)110523.csv", header = T, stringsAsFactors = T)
head(data)
str(data)
data %>%
  group_by(survey_type) %>%
  summarise(n = n())

data %>%
  group_by(your_feeling) %>%
  summarise(n = n())

data %>%
  group_by(media_portray) %>%
  summarise(n = n())

#ggplot(data, aes(x=survey_type,y=your_feeling)) + geom_boxplot(aes(fill=your_feeling))+ scale_y_continuous(breaks=c(0:10)) + ggtitle("Researcher's feelings towards insect group")
#ggplot(data, aes(x=survey_type,y=media_portray)) + geom_boxplot(aes(fill=media_portray)) + scale_y_continuous(breaks=c(0:10)) + ggtitle("Researcher's feelings towards media portray")

#have to transform the data in ordinal
data$your_feeling = factor(data$your_feeling, ordered = T)
data$media_portray = factor(data$media_portray, ordered = T)
data$media_interest = factor(data$media_interest, ordered = T)
data$media_outcome = factor(data$media_outcome, ordered = T)
data$media_your_perception = factor(data$media_your_perception, ordered = T)
data$public_perception = factor(data$public_perception, ordered = T)
data$conservation_needed=factor(data$conservation_needed, ordered = T)
data$media_conservation=factor(data$media_conservation, ordered = T)
data$more_effort_needed=factor(data$more_effort_needed, ordered = T)
data$media_management = factor(data$media_management, ordered = T)
data$time = factor(data$time, ordered = T)

str(data)
data$total_survey = as.factor(data$total_survey)
str(data)

model1a = multinom(survey_type ~ job + gender + continent_institution+time, data =data )
summary(model1a)
plot(allEffects(model1a))
anova(model1a)
emmeans(model1a, list(pairwise~survey_type))
# 
# $`pairwise differences of survey_type`
# 1          estimate     SE df t.ratio p.value
# bee - wasp  -0.0935 0.0942 16  -0.992  0.3357

tab_model(model1a,
          show.est = TRUE, 
          string.est = "Estimate", 
          show.se = TRUE,
          #show.std = TRUE,
          show.p = TRUE,
          show.stat = TRUE,
          string.stat = "zvalue",
          file = "outputmodel1.doc")

ggplot(data.frame(data), aes(x=continent_institution, fill=survey_type)) +
  geom_bar()+
  facet_wrap(~survey_type)

##### Word cloud Fig 2
#MEDIA

df <- read.csv("wordcloud_table2_110523.csv", header = T) #changed the "," to "-"; removed and and ".", changed separated words with "_" 
str(df)

df$survey_type=as.factor(df$survey_type)

# Convert the responses column into a tidy format

tidy_responses <- df %>%
  dplyr::select(survey_type, media_type) %>%
  unnest_tokens(word, media_type)


# Remove stop words and punctuation
tidy_responses <- tidy_responses %>%
  anti_join(stop_words) %>%
  drop_na() %>%
  filter(!word %in% c(",", ".", "-", "?", "!", "NA"))

word_freq <- tidy_responses %>%
  count(word)
word_freq

wordcloud2(data = word_freq, color="random-dark")

# Create a frequency table of words
word_freq_bee <- tidy_responses %>%
  filter(survey_type == "bee") %>%
  count(word)
df1 <- word_freq_bee %>% arrange(desc(n))
df1

word_freq_wasp <- tidy_responses %>%
  filter(survey_type == "wasp") %>%
  count(word)
df2 <- word_freq_wasp %>% arrange(desc(n))
df2

wordcloud2(data = df1,
           size=0.5,
           shuffle = F,
           minRotation = 1,
           maxRotation = 1,
           color="random-dark")

wordcloud2(data = df2,
           size=0.5,
           shuffle = F,
           minRotation = 1,
           maxRotation = 1,
           color="random-dark")

#wordcloud species Need to create a folder with txt file on it
cname <- file.path("~/Dropbox/Marie Curie/postdoc/manuscript in prep/frontiers in conservation and the media/wasp_wordcloud")
docs <- Corpus(DirSource(cname))

#docs <- tm_map(docs, removePunctuation) #remove punctuation
#docs <- tm_map(docs, removeNumbers) #remove numbers
docs <- tm_map(docs, tolower) #convert all characters to lower case
#docs <- tm_map(docs, removeWords, stopwords("english")) #remove common words
docs
#docs <- tm_map(docs, removeWords, c("will", "people", "britain", "british", "country", "thats")) #remove any additional specific words
#docs <- tm_map(docs, stripWhitespace) #remove whitespaces
docs <- tm_map(docs, PlainTextDocument) #ensure the document is treated as text

#Create a document term matrix
dtm <- DocumentTermMatrix(docs)

#Convert document term matrix into a dataframe and sort by frequency
df <- tidy(dtm)
df <- df[order(-df$count),c(2,3)]

wordcloud2(data = df, size =.5,shape = 'circle', color="random-dark")





name <- file.path("~/Dropbox/Marie Curie/postdoc/manuscript in prep/frontiers in conservation and the media/bee_wordcloud")
docs <- Corpus(DirSource(cname))

#docs <- tm_map(docs, removePunctuation) #remove punctuation
#docs <- tm_map(docs, removeNumbers) #remove numbers
docs <- tm_map(docs, tolower) #convert all characters to lower case
#docs <- tm_map(docs, removeWords, stopwords("english")) #remove common words
docs
#docs <- tm_map(docs, removeWords, c("will", "people", "britain", "british", "country", "thats")) #remove any additional specific words
#docs <- tm_map(docs, stripWhitespace) #remove whitespaces
docs <- tm_map(docs, PlainTextDocument) #ensure the document is treated as text


#Create a document term matrix
dtm <- DocumentTermMatrix(docs)

#Convert document term matrix into a dataframe and sort by frequency
df <- tidy(dtm)
df <- df[order(-df$count),c(2,3)]

wordcloud2(data = df, size=0.5, shape = 'circle', color="random-dark")

###### Likert plot Fig 3
str(data)
data$your_feeling = factor(data$your_feeling, ordered = T)
data$media_portray = factor(data$media_portray, ordered = T)
data$media_interest = factor(data$media_interest, ordered = T)
data$media_outcome = factor(data$media_outcome, ordered = T)
data$media_your_perception = factor(data$media_your_perception, ordered = T)
data$public_perception = factor(data$public_perception, ordered = T)
data$conservation_needed=factor(data$conservation_needed, ordered = T)
data$media_conservation=factor(data$media_conservation, ordered = T)
data$more_effort_needed=factor(data$more_effort_needed, ordered = T)
data$media_management = factor(data$media_management, ordered = T)
data$time = factor(data$time, ordered = T)


data$total_survey = as.factor(data$total_survey)
str(data)

#question a
clm1 = clm(your_feeling ~ survey_type,data=data)
summary(clm1)
emmeans(clm1, list(pairwise~survey_type))
anova(clm1, type = "II")

data %>%
  group_by(your_feeling,survey_type) %>%
  summarise(n = n())

#question b
clm2 <- clm(media_portray ~ survey_type, data=data)
summary(clm2)
emmeans(clm2, list(pairwise~survey_type))

data %>%
  group_by(media_portray,survey_type) %>%
  summarise(n = n())

# clm2b <- clm(media_portray ~ survey_type +continent_institution, data=data)
# summary(clm2b)
# anova(clm2b)
# emmeans(clm2b, list(pairwise~survey_type))
# emmeans(clm2b, list(pairwise~continent_institution))

# question c
clm6 = clm(public_perception ~ survey_type,data=data)
summary(clm6)
emmeans(clm6, list(pairwise~survey_type))

data %>%
  group_by(public_perception,survey_type) %>%
  summarise(n = n())

# clm6a = clm(public_perception ~ survey_type +institution_country,data=data)
# summary(clm6a)
# emmeans(clm6a, list(pairwise~survey_type))

#question d
clm3 = clm(media_interest ~ survey_type,data=data)
summary(clm3)
emmeans(clm3, list(pairwise~survey_type))

data %>%
  group_by(media_interest,survey_type) %>%
  summarise(n = n())


#question e
clm4 = clm(media_outcome ~ survey_type,data=data)
summary(clm4)
emmeans(clm4, list(pairwise~survey_type))

data %>%
  group_by(media_outcome,survey_type) %>%
  summarise(n = n())

#question f

clm5 = clm(media_your_perception ~ survey_type,data=data)
summary(clm5)
emmeans(clm5, list(pairwise~survey_type))

data %>%
  group_by(media_your_perception,survey_type) %>%
  summarise(n = n())

#question g
clm7 = clm(conservation_needed ~ survey_type,data=data)
summary(clm7)
emmeans(clm7, list(pairwise~survey_type))

data %>%
  group_by(conservation_needed,survey_type) %>%
  summarise(n = n())

# question h
clm8 = clm(media_conservation ~ survey_type,data=data)
summary(clm8)
emmeans(clm8, list(pairwise~survey_type))

data %>%
  group_by(media_conservation,survey_type) %>%
  summarise(n = n())

# question i
data$more_effort_needed
clm10 = clm(more_effort_needed ~ survey_type,data=data)
summary(clm10)
emmeans(clm10, list(pairwise~survey_type))

b=data %>%
  group_by(more_effort_needed, survey_type) %>%
  summarise(n = n())
i1 <- as_tibble(a)
print(i1,n=22)

#question j
clm9 = clm(media_management ~ survey_type,data=data)
summary(clm9)
emmeans(clm9, list(pairwise~survey_type))

data %>%
  group_by(media_management,survey_type) %>%
  summarise(n = n())

a=data %>%
  group_by(media_management, survey_type) %>%
  summarise(n = n())
i1 <- as_tibble(a)
print(i1,n=22)

# Figure 4 

data_country_public <- read.csv("Public_perception_long.csv", header = T, stringsAsFactors=T)
head(data_country_public)
str(data_country_public)

data_country_public$rating <- factor(data_country_public$rating,                                    # Change ordering manually
                                     levels = c("1_lik", "2_lik", "3_lik", "4_lik", "5_lik", "6_lik", "7_lik", "8_lik", "9_lik", "10_lik"))



gg =ggplot(data_country_public, aes(x = rating, y = country, color = rating)) +
  geom_point(aes(size = count))+
  scale_color_manual(values = c("#C1526D", "#CC7386", "#D593A0", "#DCB3BA", "#E1D2D5", "#D0D7DF", "#AAC0D7", "#81A9CF", "#4E94C7", "#0080C0")) +
  facet_wrap(~organism)+
  theme_bw()  
gg

gg + theme(legend.position='bottom')


#scale_color_manual(values = c("#C1526D", "#CC7386", "#D593A0", "#DCB3BA", "#E1D2D5", "#D0D7DF", "#AAC0D7", "#81A9CF", "#4E94C7", "#0080C0")) +
#scale_size(range = c(1, 13)) + # Adjust the range of points size
#theme_bw()
#graph2ppt(file="Public_perception_260423.pptx",width=7, height=5)

# Publics interest on Google Trends

# most surveys from BR and USA
data_country <- read.csv("bee_wasp_USA_BR_t.csv", header = T, stringsAsFactors=T)
head(data_country)
str(data_country)

model1 = glm(searches~ organism+media+country, data=data_country, family=poisson)
model1
summary(model1)
emmeans(model1, pairwise~organism, adjust="fdr" , type="response") 

plot(allEffects(model1))

p1 <- ggpredict(model1, c("organism", "media", "country"))
plot(p1, connect.lines = TRUE)

# AIM 3 analysing the questions d and e separately
data_long <- read.csv("before_after.csv", header = T, stringsAsFactors=T)
head(data_long)
str(data_long)

data_long$time = factor(data_long$time, ordered = T)
data_long$rating = factor(data_long$rating, ordered = T)
data_long$question = factor(data_long$question, ordered = T)
data_long$survey_type = factor(data_long$survey_type, levels=unique(data_long$survey_type))

data_long$Likert.f=factor(data_long$rating,ordered = T)
model3 = clmm(Likert.f ~ survey_type + question+ survey_type:question + (1|ID),
              data = data_long,
              threshold = "equidistant")
library(RVAideMemoire)
Anova.clmm(model3, type="II")

marginal= emmeans(model3, ~ survey_type+question)
pairs(marginal, adjust ="tukey")

library(multcomp)
cld(marginal, Letters = T)


# survey_type question       emmean    SE  df asymp.LCL asymp.UCL .group
# wasp        media_interest -1.069 0.526 Inf    -2.100   -0.0376  T    
# wasp        media_outcome   0.799 0.518 Inf    -0.216    1.8135   R   
# bee         media_interest  4.017 0.645 Inf     2.753    5.2812    U  
# bee         media_outcome   4.909 0.706 Inf     3.525    6.2927    U  

# more conservation per country Figu 5
data_country <- read.csv("country_more_effort1.csv", header = T, stringsAsFactors=T)
head(data_country)
str(data_country)

data_country$rating <- factor(data_country$rating,                                    # Change ordering manually
                              levels = c("1_lik", "2_lik", "3_lik", "4_lik", "5_lik", "6_lik", "7_lik", "8_lik", "9_lik", "10_lik"))


model3 = glm(country.1 ~ organism + rating + country, family = poisson(link = log), data =data_country )
summary(model3)
plot(allEffects(model3))
anova(model3)
emmeans(model3, list(pairwise~organism*country))


gg =ggplot(data_country, aes(x = rating, y = country, color = rating)) +
  geom_point(aes(size = country.1))+
  scale_color_manual(values = c("#C1526D", "#CC7386", "#D593A0", "#DCB3BA", "#E1D2D5", "#D0D7DF", "#AAC0D7", "#81A9CF", "#4E94C7", "#0080C0")) +
  facet_wrap(~organism)+
  theme_bw()     
gg + theme(legend.position='bottom')
