Each CSV is one weekly scrape by one collector (Dakota, David, Gabriel, Marco). This notebook:
# --- locate files (works with the unzipped folder or the .zip) ---------------
data_dir <- params$data_path
if (grepl("\\.zip$", data_dir, ignore.case = TRUE)) {
unzip(data_dir, exdir = tempdir())
data_dir <- tempdir()
}
files <- list.files(data_dir, pattern = "\\.csv$", recursive = TRUE,
full.names = TRUE, ignore.case = TRUE)
stopifnot(length(files) > 0)
# Read everything as character first (text fields contain quotes/newlines), convert later
raw <- map_dfr(files, function(f) {
read_csv(f, col_types = cols(.default = col_character()), progress = FALSE) |>
mutate(file = basename(f))
})
cat("Rows read:", nrow(raw), "from", length(files), "files\n")
## Rows read: 3050 from 17 files
posts <- raw |>
mutate(
collector = str_to_title(str_extract(file, "^[^_]+")),
week_file = as.integer(str_extract(file, "(?<=week)\\d+")),
# created_at is sometimes missing -> fall back to indexed_at. Formats are mixed
# (with/without milliseconds), which ymd_hms handles.
posted_at = coalesce(ymd_hms(created_at, quiet = TRUE),
ymd_hms(indexed_at, quiet = TRUE)),
across(c(reply_count, repost_count, like_count, quote_count, bookmark_count),
~ replace_na(as.numeric(.x), 0)),
is_reply = !is.na(in_reply_to)
) |>
# weekly files overlap: keep one row per post, preferring the latest snapshot
arrange(desc(week_file)) |>
distinct(uri, .keep_all = TRUE) |>
filter(!is.na(text), !is.na(posted_at))
if (isTRUE(params$english_only)) {
posts <- posts |> filter(is.na(langs) | str_detect(langs, "^en"))
}
if (!is.na(params$start_date)) {
posts <- posts |> filter(as_date(posted_at) >= as_date(params$start_date))
}
posts <- posts |>
mutate(
date = as_date(posted_at),
week = floor_date(date, "week", week_start = 1),
month = floor_date(date, "month"),
engagement = like_count + repost_count + reply_count + quote_count,
text_clean = text |>
str_replace_all("https?://\\S+|www\\.\\S+", " ") |> # URLs
str_replace_all("\\b\\S+\\.(com|org|net|io|cc|social)\\S*", " ") |> # bare domains
str_replace_all("@\\S+", " ") |> # mentions
str_replace_all("&", " and ") |>
iconv("UTF-8", "ASCII", sub = " ") |> # drop emoji / odd symbols
str_replace_all("[^A-Za-z#'\\s]", " ") |> # keep letters, hashtags, apostrophes
str_squish() |> str_to_lower()
) |>
select(uri, collector, posted_at, date, week, month, text, text_clean,
like_count, repost_count, reply_count, quote_count, engagement,
is_reply, tags)
cat("Unique, usable posts:", nrow(posts), "\n")
## Unique, usable posts: 596
posts |> count(collector, name = "posts") |> arrange(desc(posts))
# Categorical colours (fixed order per collector) + diverging pair for sentiment
collector_cols <- setNames(c("#257de0", "#f47230", "#00b894", "#6a4ce2"),
sort(unique(posts$collector)))[seq_along(unique(posts$collector))]
sent_cols <- c(positive = "#257de0", neutral = "#9c9c9c", negative = "#f47230")
base_layout <- function(p, title, xlab = NULL, ylab = NULL) {
p |> layout(title = list(text = title, x = 0, font = list(size = 15)),
xaxis = list(title = xlab, showgrid = FALSE),
yaxis = list(title = ylab, gridcolor = "#e6e6e6", zeroline = FALSE),
legend = list(orientation = "h", y = -0.2),
hovermode = "x unified")
}
daily <- posts |> count(date, collector)
plot_ly(daily, x = ~date, y = ~n, color = ~collector, colors = collector_cols,
type = "bar") |>
layout(barmode = "stack") |>
base_layout("Posts per day, by collector", ylab = "Posts")
monthly <- posts |>
group_by(month) |>
summarise(posts = n(), avg_likes = mean(like_count),
avg_engagement = mean(engagement), .groups = "drop")
plot_ly(monthly, x = ~month, y = ~posts, type = "scatter", mode = "lines+markers",
line = list(color = "#257de0", width = 2), marker = list(size = 8, color = "#257de0"),
name = "Posts") |>
base_layout("Posts per month (all collectors)", ylab = "Posts")
weekly_eng <- posts |>
group_by(week, collector) |>
summarise(n = n(), avg_engagement = mean(engagement), .groups = "drop") |>
filter(n >= params$min_posts_week)
plot_ly(weekly_eng, x = ~week, y = ~avg_engagement, color = ~collector, colors = collector_cols,
type = "scatter", mode = "lines+markers", text = ~paste("posts:", n),
hovertemplate = "%{y:.1f} avg engagement<br>%{text}<extra>%{fullData.name}</extra>") |>
base_layout("Average engagement per post, weekly (likes + reposts + replies + quotes)",
ylab = "Avg engagement")
custom_stop <- c("amp", "rt", "gt", "lt", "s", "t", "m", "re", "ve", "ll", "d",
"https", "http", "bsky", "app", "social", "via", "just", "like",
"get", "got", "will", "can", "one", "also", "new")
words <- posts |>
select(uri, collector, date, week, month, text_clean) |>
unnest_tokens(word, text_clean) |>
filter(!word %in% stop_words$word,
!word %in% custom_stop,
nchar(word) > 2,
!str_detect(word, "^[0-9]+$"))
cat("Total tokens after cleaning:", nrow(words), " | unique words:", n_distinct(words$word), "\n")
## Total tokens after cleaning: 9899 | unique words: 3127
top_overall <- words |> count(word, sort = TRUE) |> slice_head(n = params$top_n)
plot_ly(top_overall, x = ~n, y = ~reorder(word, n), type = "bar", orientation = "h",
marker = list(color = "#257de0")) |>
layout(title = list(text = "Top words (all posts)", x = 0),
xaxis = list(title = "Count", gridcolor = "#e6e6e6"),
yaxis = list(title = ""), margin = list(l = 110))
Each collector appears to have followed a different topic, so words are compared per collector:
top_by_collector <- words |>
count(collector, word, sort = TRUE) |>
group_by(collector) |> slice_head(n = 10) |> ungroup()
plots <- map(sort(unique(top_by_collector$collector)), function(cl) {
d <- top_by_collector |> filter(collector == cl)
plot_ly(d, x = ~n, y = ~reorder(word, n), type = "bar", orientation = "h",
marker = list(color = collector_cols[[cl]]), name = cl, showlegend = FALSE) |>
layout(annotations = list(list(text = paste0("<b>", cl, "</b>"), x = 0.5, y = 1.05,
xref = "paper", yref = "paper", showarrow = FALSE)),
yaxis = list(title = ""), xaxis = list(title = "Count"))
})
subplot(plots, nrows = 2, margin = 0.08, titleX = TRUE) |>
layout(title = list(text = "Top 10 words per collector", x = 0), margin = list(l = 90, t = 70))
Words that are especially characteristic of each collector’s posts, not just common ones:
tfidf <- words |>
count(collector, word) |>
bind_tf_idf(word, collector, n) |>
group_by(collector) |> slice_max(tf_idf, n = 8, with_ties = FALSE) |> ungroup()
plots <- map(sort(unique(tfidf$collector)), function(cl) {
d <- tfidf |> filter(collector == cl)
plot_ly(d, x = ~tf_idf, y = ~reorder(word, tf_idf), type = "bar", orientation = "h",
marker = list(color = collector_cols[[cl]]), showlegend = FALSE) |>
layout(annotations = list(list(text = paste0("<b>", cl, "</b>"), x = 0.5, y = 1.05,
xref = "paper", yref = "paper", showarrow = FALSE)),
yaxis = list(title = ""), xaxis = list(title = "TF-IDF"))
})
subplot(plots, nrows = 2, margin = 0.08, titleX = TRUE) |>
layout(title = list(text = "Most distinctive words per collector", x = 0), margin = list(l = 90, t = 70))
Weekly share of all words (per 1,000 words) for the most frequent terms:
top_terms <- top_overall$word[1:min(8, nrow(top_overall))]
word_trend <- words |>
group_by(week) |> mutate(week_total = n()) |> ungroup() |>
filter(word %in% top_terms) |>
group_by(week, word, week_total) |>
summarise(n = n(), .groups = "drop") |>
mutate(per_1000 = n / week_total * 1000) |>
filter(week_total >= 50) # skip near-empty weeks
plot_ly(word_trend, x = ~week, y = ~per_1000, color = ~word,
type = "scatter", mode = "lines+markers") |>
base_layout("Top terms over time (per 1,000 words, weekly)", ylab = "Per 1,000 words")
Pick your own terms to track (edit the vector below):
my_terms <- c("sales", "game", "launch") # <- edit me
custom_trend <- words |>
group_by(week) |> mutate(week_total = n()) |> ungroup() |>
filter(word %in% my_terms, week_total >= 50) |>
count(week, word, week_total) |>
mutate(per_1000 = n / week_total * 1000)
if (nrow(custom_trend) > 0) {
plot_ly(custom_trend, x = ~week, y = ~per_1000, color = ~word,
type = "scatter", mode = "lines+markers") |>
base_layout("Selected terms over time", ylab = "Per 1,000 words")
}
Sentiment uses the Bing lexicon (positive / negative
word lists, built into tidytext, no download needed). A
post’s score is positive words - negative words. Posts with
no lexicon words count as neutral.
Lexicons don’t know your topic. In gaming news, words like hollow (Hollow Knight), duty (Call of Duty), gross (gross sales), killer, boss or hit are not really negative. The vector below removes such false signals. Check the “driving words” chart in 5.2 and extend it.
# Words to ignore for sentiment because they are names/jargon in this dataset
sentiment_ignore <- c("hollow", "duty", "gross", "killer", "kill", "boss", "bosses", "hit",
"hits", "beat", "war", "fall", "cold", "shot", "fire", "trump",
"like", "well", "work", "top", "free", "plus", "lead", "support",
"silk", "knight", "black", "dark", "wicked", "crash")
bing <- get_sentiments("bing") |> filter(!word %in% sentiment_ignore)
# Tokenize WITHOUT removing stop words (they aren't in Bing anyway)
sent_words <- posts |>
select(uri, text_clean) |>
unnest_tokens(word, text_clean) |>
inner_join(bing, by = "word", relationship = "many-to-many")
post_sent <- sent_words |>
count(uri, sentiment) |>
pivot_wider(names_from = sentiment, values_from = n, values_fill = 0)
posts_s <- posts |>
left_join(post_sent, by = "uri") |>
mutate(positive = replace_na(positive, 0), negative = replace_na(negative, 0),
score = positive - negative,
label = case_when(score > 0 ~ "positive", score < 0 ~ "negative", TRUE ~ "neutral"),
label = factor(label, levels = c("negative", "neutral", "positive")))
posts_s |> count(label) |> mutate(share = percent(n / sum(n), accuracy = 0.1))
label_counts <- posts_s |> count(collector, label)
plot_ly(label_counts, x = ~collector, y = ~n, color = ~label, colors = sent_cols,
type = "bar") |>
layout(barmode = "stack",
title = list(text = "Post sentiment by collector", x = 0),
xaxis = list(title = ""), yaxis = list(title = "Posts", gridcolor = "#e6e6e6"),
legend = list(orientation = "h", y = -0.15))
plot_ly(posts_s, x = ~score, color = ~collector, colors = collector_cols,
type = "histogram", alpha = 0.7, nbinsx = 21) |>
layout(barmode = "overlay",
title = list(text = "Distribution of post sentiment scores", x = 0),
xaxis = list(title = "Score (positive words - negative words)"),
yaxis = list(title = "Posts", gridcolor = "#e6e6e6"),
legend = list(orientation = "h", y = -0.2))
driving <- sent_words |>
count(word, sentiment, sort = TRUE) |>
group_by(sentiment) |> slice_head(n = 12) |> ungroup() |>
mutate(n_signed = if_else(sentiment == "negative", -n, n))
plot_ly(driving, x = ~n_signed, y = ~reorder(word, n_signed), color = ~sentiment,
colors = sent_cols, type = "bar", orientation = "h",
text = ~n, hovertemplate = "%{y}: %{text}<extra></extra>") |>
layout(title = list(text = "Top positive and negative words", x = 0),
xaxis = list(title = "Count (negative shown to the left)", gridcolor = "#e6e6e6"),
yaxis = list(title = ""), margin = list(l = 100),
legend = list(orientation = "h", y = -0.15))
weekly_sent <- posts_s |>
group_by(week) |>
summarise(n = n(), mean_score = mean(score),
pos_share = mean(label == "positive"),
neu_share = mean(label == "neutral"),
neg_share = mean(label == "negative"), .groups = "drop") |>
filter(n >= params$min_posts_week)
plot_ly(weekly_sent, x = ~week, y = ~mean_score, type = "scatter", mode = "lines+markers",
line = list(color = "#257de0", width = 2), marker = list(size = 8, color = "#257de0"),
text = ~paste("posts:", n),
hovertemplate = "mean score %{y:.2f}<br>%{text}<extra></extra>") |>
base_layout("Average sentiment score per post, weekly", ylab = "Mean score") |>
layout(shapes = list(list(type = "line", x0 = 0, x1 = 1, xref = "paper", y0 = 0, y1 = 0,
line = list(color = "#9c9c9c", dash = "dot"))))
plot_ly(weekly_sent, x = ~week, type = "bar") |>
add_bars(y = ~pos_share, name = "positive", marker = list(color = sent_cols[["positive"]])) |>
add_bars(y = ~neu_share, name = "neutral", marker = list(color = sent_cols[["neutral"]])) |>
add_bars(y = ~neg_share, name = "negative", marker = list(color = sent_cols[["negative"]])) |>
layout(barmode = "stack") |>
base_layout("Share of positive / neutral / negative posts, weekly") |>
layout(yaxis = list(tickformat = ".0%", title = "Share of posts"))
weekly_sent_c <- posts_s |>
group_by(week, collector) |>
summarise(n = n(), mean_score = mean(score), .groups = "drop") |>
filter(n >= params$min_posts_week)
plot_ly(weekly_sent_c, x = ~week, y = ~mean_score, color = ~collector, colors = collector_cols,
type = "scatter", mode = "lines+markers", text = ~paste("posts:", n),
hovertemplate = "mean score %{y:.2f}<br>%{text}<extra>%{fullData.name}</extra>") |>
base_layout("Average sentiment per post, weekly, by collector", ylab = "Mean score")
# Trailing mean ignoring NA (no extra packages needed)
slider_mean <- function(x, k) {
vapply(seq_along(x), function(i) mean(x[max(1, i - k + 1):i], na.rm = TRUE), numeric(1))
}
# Smooth daily view: 7-day rolling mean of the daily average score
daily_sent <- posts_s |>
group_by(date) |> summarise(n = n(), score = mean(score), .groups = "drop") |>
complete(date = seq(min(date), max(date), by = "day"), fill = list(n = 0)) |>
arrange(date)
daily_sent$roll <- slider_mean(daily_sent$score, 7)
plot_ly(daily_sent, x = ~date) |>
add_markers(y = ~score, name = "daily mean", marker = list(color = "#9c9c9c", size = 5, opacity = 0.5)) |>
add_lines(y = ~roll, name = "7-day rolling mean", line = list(color = "#f47230", width = 2.5)) |>
base_layout("Daily sentiment with 7-day rolling average", ylab = "Mean score")
plot_ly(posts_s |> filter(engagement > 0),
x = ~score, y = ~engagement, color = ~collector, colors = collector_cols,
type = "scatter", mode = "markers", marker = list(size = 8, opacity = 0.65),
text = ~str_trunc(text, 120), hovertemplate = "%{text}<br>score %{x}, engagement %{y}<extra>%{fullData.name}</extra>") |>
layout(title = list(text = "Sentiment score vs. engagement (posts with engagement > 0)", x = 0),
xaxis = list(title = "Sentiment score"),
yaxis = list(title = "Engagement (log scale)", type = "log", gridcolor = "#e6e6e6"),
legend = list(orientation = "h", y = -0.2))
posts_s |>
group_by(label) |>
summarise(posts = n(), mean_engagement = round(mean(engagement), 2),
median_engagement = median(engagement), .groups = "drop")
posts_s |>
filter(label != "neutral") |>
arrange(desc(abs(score))) |>
slice_head(n = 40) |>
transmute(date, collector, score, likes = like_count, text = str_trunc(text, 250)) |>
datatable(rownames = FALSE, options = list(pageLength = 10, scrollX = TRUE))
uri; the latest snapshot’s like/repost
counts win.created_at is missing for some
posts, so indexed_at is used in those cases. Most of the
data is from mid-2026 onward, which is why early weeks are filtered out
by min_posts_week (change in the YAML
params).sentiment_ignore for your topics. For a richer score, add
AFINN or NRC (textdata package) or a model-based approach
such as sentimentr or a transformer.topicmodels/stm), comparing sentiment
before/after key dates (e.g., a game launch), or network of co-occurring
words.sessionInfo()
## R version 4.6.2 (2026-10-29)
## Platform: x86_64-pc-linux-gnu
## Running under: Ubuntu 24.04.5 LTS
##
## Matrix products: default
## BLAS: /usr/lib/x86_64-linux-gnu/openblas-pthread/libblas.so.3
## LAPACK: /usr/lib/x86_64-linux-gnu/openblas-pthread/libopenblasp-r0.3.26.so; LAPACK version 3.12.0
##
## locale:
## [1] LC_CTYPE=C.UTF-8 LC_NUMERIC=C LC_TIME=C.UTF-8
## [4] LC_COLLATE=C.UTF-8 LC_MONETARY=C.UTF-8 LC_MESSAGES=C.UTF-8
## [7] LC_PAPER=C.UTF-8 LC_NAME=C LC_ADDRESS=C
## [10] LC_TELEPHONE=C LC_MEASUREMENT=C.UTF-8 LC_IDENTIFICATION=C
##
## time zone: UTC
## tzcode source: system (glibc)
##
## attached base packages:
## [1] stats graphics grDevices utils datasets methods base
##
## other attached packages:
## [1] scales_1.4.0 DT_0.34.0 plotly_4.12.1 tidytext_0.4.3
## [5] lubridate_1.9.5 forcats_1.0.1 stringr_1.6.0 dplyr_1.2.1
## [9] purrr_1.2.2 readr_2.2.0 tidyr_1.3.2 tibble_3.3.1
## [13] ggplot2_4.0.4 tidyverse_2.0.0
##
## loaded via a namespace (and not attached):
## [1] janeaustenr_1.0.0 sass_0.5.0 generics_0.1.4
## [4] stringi_1.8.9 lattice_0.22-9 hms_1.1.4
## [7] digest_0.6.39 magrittr_2.0.5 evaluate_1.0.5
## [10] grid_4.6.2 timechange_0.4.0 RColorBrewer_1.1-3
## [13] fastmap_1.2.0 jsonlite_2.0.0 Matrix_1.7-5
## [16] httr_1.4.9 crosstalk_1.2.2 viridisLite_0.4.3
## [19] jquerylib_0.1.4 cli_3.6.6 crayon_1.5.3
## [22] rlang_1.3.0 tokenizers_0.3.0 bit64_4.8.6
## [25] withr_3.0.3 cachem_1.1.0 yaml_2.3.12
## [28] otel_0.3.0 parallel_4.6.2 tools_4.6.2
## [31] tzdb_0.5.0 vctrs_0.7.3 R6_2.6.1
## [34] lifecycle_1.0.5 bit_4.6.0 htmlwidgets_1.6.4
## [37] vroom_1.7.1 pkgconfig_2.0.3 pillar_1.11.1
## [40] bslib_0.12.0 gtable_0.3.6 glue_1.8.1
## [43] data.table_1.18.6.1 Rcpp_1.1.2 xfun_0.62
## [46] tidyselect_1.2.1 rstudioapi_0.19.0 knitr_1.52
## [49] farver_2.1.2 htmltools_0.5.9 SnowballC_0.7.1
## [52] rmarkdown_2.32 compiler_4.6.2 S7_1.0.0