Start tidyverse migration
Change-Id: Ifc972de789c22e2ff43159740d7f1fa7125e1ef2
diff --git a/demo/alternativesOverTime.R b/demo/alternativesOverTime.R
index 7866121..443fbe4 100755
--- a/demo/alternativesOverTime.R
+++ b/demo/alternativesOverTime.R
@@ -4,26 +4,25 @@
#
library(RKorAPClient)
library(ggplot2)
-library(reshape2)
+library(tidyr)
+library(dplyr)
library(plotly)
library(htmlwidgets)
alternativesOverTime <- function(alternatives, years, kco = new("KorAPConnection", verbose=TRUE)) {
- df = data.frame(year=years)
vc = "textType = /Zeit.*/ & pubDate in"
- urls <- data.frame()
- for (v in alternatives) {
- df[v] <- sapply(df$year, function(y) {
- kqo <- corpusQuery(kco, query=v, vc=paste(vc, y))
- urls <<- rbind(urls, data.frame(Variant=v, year=y, url=kqo@webUIRequestUrl))
- kqo@totalResults
- })
- }
- df$total <- apply(df[,alternatives], 1, sum)
- df <- merge(melt(df, measure.vars = alternatives, value.name = "afreq", variable.name = "Variant"),
- urls, by=c("Variant", "year"))
- df$ci <- t(sapply(Map(prop.test, df$afreq, df$total), "[[","conf.int"))
- df$share <- df$afreq / df$total
+ df <- data.frame(matrix(ncol = length(alternatives), nrow = length(years))) %>%
+ setNames(alternatives) %>%
+ mutate(year = years) %>%
+ pivot_longer(cols = alternatives) %>%
+ rowwise %>% mutate(value = corpusQuery(kco, query=name, vc=paste(vc, year))@totalResults) %>%
+ pivot_wider(id_cols= year, names_from = name) %>%
+ mutate(total = rowSums(.[alternatives])) %>%
+ pivot_longer(cols = alternatives) %>%
+ mutate(share = value / total) %>%
+ rowwise %>% mutate(url = corpusQuery(kco, query=name, vc=paste(vc, year))@webUIRequestUrl) %>%
+ rename(Variant = name)
+ df$ci <- t(sapply(Map(prop.test, df$value, df$total), "[[","conf.int"))
g <- ggplot(data = df, mapping = aes(x = year, y = share, color=Variant, fill=Variant)) +
geom_ribbon(aes(ymin=ci[, 1], ymax=ci[, 2], color=Variant, fill=Variant), alpha=.3, linetype=0) +
geom_line() +
@@ -36,7 +35,7 @@
for (i in 1:length(alternatives)) {
vdata <- df[df$Variant==alternatives[i],]
pp$x$data[[2+i]]$customdata <- vdata$url
- pp$x$data[[2+i]]$text <- sprintf("%s<br />absolute: %d / %d", pp$x$data[[2+i]]$text, vdata$afreq, vdata$total)
+ pp$x$data[[2+i]]$text <- sprintf("%s<br />absolute: %d / %d", pp$x$data[[2+i]]$text, vdata$value, vdata$total)
}
ppp <- onRender(pp, "function(el, x) { el.on('plotly_click', function(d) { var url=d.points[0].customdata; window.open(url, 'korap') })}")
print(ppp)