pablobarbera / Rfacebook

Dev version of Rfacebook package: Access to Facebook API via R
http://cran.r-project.org/web/packages/Rfacebook
350 stars 250 forks source link

Analyzing data from a Facebook page: a weekly analysis #162

Open andreaangeli opened 6 years ago

andreaangeli commented 6 years ago

Hi @pablobarbera, from the very useful exemple by you I was wondering if it were possible to aggregate the metrics (likes, coments and shares) by week (instead by month like you do) in order to compute the median count for temporarely shorter analysis?

In particular how can I manipulate the code? I'm a newbie

## convert Facebook date format to R date format
format.facebook.date <- function(datestring) {
    date <- as.POSIXct(datestring, format = "%Y-%m-%dT%H:%M:%S+0000", tz = "GMT")
}
## aggregate metric counts over month
aggregate.metric <- function(metric) {
    m <- aggregate(page[[paste0(metric, "_count")]], list(month = page$month), 
        mean)
    m$month <- as.Date(paste0(m$month, "-15"))
    m$metric <- metric
    return(m)
}
# create data frame with average metric counts per month
page$datetime <- format.facebook.date(page$created_time)
page$month <- format(page$datetime, "%Y-%m")
df.list <- lapply(c("likes", "comments", "shares"), aggregate.metric)
df <- do.call(rbind, df.list)
# visualize evolution in metric
library(ggplot2)
library(scales)
ggplot(df, aes(x = month, y = x, group = metric)) + geom_line(aes(color = metric)) + 
    scale_x_date(date_breaks = "years", labels = date_format("%Y")) + scale_y_log10("Average count per post", 
    breaks = c(10, 100, 1000, 10000, 50000)) + theme_bw() + theme(axis.title.x = element_blank())