---
title: "Facebook Key Metrics Analysis"
author: "François Pelletier"
date: "7 novembre 2015"
output:
  html_document:
    highlight: tango
    keep_md: yes
    theme: cerulean
    toc: yes
  pdf_document:
    toc: yes
---

```{r}
library(data.table)
library(lubridate)
library(magrittr)
library(ggplot2)
library(dplyr)

# Setup your own Facebook key metrics here (csv export from XLS file)
page_key_metrics_raw <- fread("page_key_metrics.csv",header = TRUE)
page_key_metrics_raw$Posted2 <- page_key_metrics_raw$Posted %>% 
  lubridate::parse_date_time("m/d/yR")
page_key_metrics_raw$substr_post <- page_key_metrics_raw$`Post Message` %>% substr(0,70)
```

## Reach

```{r, dev='CairoPNG'}
ggplot(data=page_key_metrics_raw,
       aes(x=Posted2,
           y=`Lifetime Post organic reach`,
           color=Type)) + 
  geom_line() + 
  ggtitle("Lifetime Post Organic Reach over time by type") +
  ggplot2::xlab("Time posted")
```

```{r results='asis'}
page_key_metrics_raw[order(page_key_metrics_raw$`Lifetime Post organic reach`,
                           decreasing = TRUE),
                     .(substr_post,Permalink,Posted2,`Lifetime Post organic reach`)] %>% 
  head(10) %>% pander::pander()
```



## Impressions

```{r, dev='CairoPNG'}
ggplot(data=page_key_metrics_raw,
       aes(x=Posted2,
           y=`Lifetime Post Organic Impressions`,
           color=Type)) + 
  geom_line() + 
  ggtitle("Lifetime Post Organic Impressions over time by type") +
  ggplot2::xlab("Time posted")
```

```{r results='asis'}
page_key_metrics_raw[order(page_key_metrics_raw$`Lifetime Post Organic Impressions`,
                           decreasing = TRUE),
                     .(substr_post,Permalink,Posted2,`Lifetime Post Organic Impressions`)] %>% 
  head(10) %>% pander::pander()
```

## Engaged Users

```{r, dev='CairoPNG'}
# correction
page_key_metrics_raw$`Lifetime Engaged Users` <- 
  page_key_metrics_raw$`Lifetime Engaged Users` %>% as.numeric

ggplot(data=page_key_metrics_raw,
       aes(x=Posted2,
           y=`Lifetime Engaged Users`,
           color=Type)) + 
  geom_line() + 
  ggtitle("Lifetime Engaged Users over time by type") +
  ggplot2::xlab("Time posted")
```

```{r results='asis'}
page_key_metrics_raw[order(page_key_metrics_raw$`Lifetime Engaged Users`,
                           decreasing = TRUE),
                     .(substr_post,Permalink,Posted2,`Lifetime Engaged Users`)] %>% 
  head(10) %>% pander::pander()
```

## Type

```{r}
data_mean_reach <- page_key_metrics_raw[,.(Type,`Lifetime Post organic reach`,Posted2)] %>%
  mutate(month_posted = lubridate::month(Posted2,label=TRUE)) %>%
  group_by(Type,month_posted) %>% summarise(mean_reach = mean(`Lifetime Post organic reach`))
```

```{r, dev='CairoPNG'}
ggplot(data=data_mean_reach, 
       aes(x=Type,y=mean_reach,fill=Type)) + 
  facet_grid(. ~ month_posted) + 
  geom_bar(stat="identity") +
  ggtitle("Mean reach by post type by month") + 
  ylab("Mean reach")
```


