-
Notifications
You must be signed in to change notification settings - Fork 19
/
README.Rmd
329 lines (275 loc) · 12.8 KB
/
README.Rmd
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
---
output: github_document
---
```{r global_options, include = FALSE}
knitr::opts_chunk$set(
collapse = TRUE,
comment = "#>",
fig.path = "man/figures/README-",
out.width = "100%"
)
```
# rwhatsapp
<!-- badges: start -->
[![CRAN status](https://www.r-pkg.org/badges/version/rwhatsapp)](https://cran.r-project.org/package=rwhatsapp)
[![Coverage Status](https://codecov.io/gh/JBGruber/rwhatsapp/branch/master/graph/badge.svg)](https://app.codecov.io/gh/JBGruber/rwhatsapp?branch=master)
[![Project Status: Active – The project has reached a stable, usable state and is being actively developed.](https://www.repostatus.org/badges/latest/active.svg)](https://www.repostatus.org/#active)
![Downloads](https://cranlogs.r-pkg.org/badges/grand-total/rwhatsapp)
[![R-CMD-check](https://github.com/JBGruber/rwhatsapp/actions/workflows/R-CMD-check.yaml/badge.svg)](https://github.com/JBGruber/rwhatsapp/actions/workflows/R-CMD-check.yaml)
[![say-thanks](https://img.shields.io/badge/Say%20Thanks-!-1EAEDB.svg)](https://saythanks.io/to/JBGruber)
<!-- badges: end -->
## Motivation
`rwhatsapp` is a small yet robust package that provides some infrastructure to work with WhatsApp text data in `R`.
WhatsApp seems to become increasingly important not just as a messaging service but also as a social network---thanks to its group chat capabilities.
Furthermore, retrieving chat logs from the Android or iOS app is very straightforward:
Simply choose `More` in the menu of a chat, then `Export chat` and export the history to a txt file.
```{r results = 'asis', echo = FALSE, tidy = FALSE}
cat('<img src="man/figures/1.jpg" width="250" /> <img src="man/figures/2.jpg" width="250" /> <img src="man/figures/3.jpg" width="250" />')
```
This package is intended to make the first step of analysing WhatsApp text data as easy as possible: reading your chat history into `R`.
This should work, no matter which device or locale you used to retrieve the `txt` or `zip` file containing your conversations.
**If you have ideas for what can be useful functions or if you have problems with an existing function, please don't hesitate to file an [issue report](https://github.com/JBGruber/rwhatsapp/issues)**.
## Installation
```{r eval = FALSE}
install.packages("rwhatsapp")
```
Or install the GitHub version:
```{r eval = FALSE}
remotes::install_github("JBGruber/rwhatsapp")
```
## Demo
The package comes with a small sample that you can use to get going.
```{r}
history <- system.file("extdata", "sample.txt", package = "rwhatsapp")
```
The main function of the package, `rwa_read()` can handle `txt` (and `zip`) files directly, which means that you can simply provide the path to a file to get started:
```{r read}
library("rwhatsapp")
chat <- rwa_read(history)
chat
```
Now, this isn't very interesting so you will probably want to use your own data.
For this demonstration, I use one of my own chat logs from a conversation with friends:^[I remove messages with author = `NA` as these are just info messages from WhatsApp like *"Messages to this group are now secured with end-to-end encryption. Tap for more info"*.]
```{r read_chat, message=FALSE}
library("dplyr")
chat <- rwa_read("/home/johannes/WhatsApp Chat.txt") %>%
filter(!is.na(author)) # remove messages without author
chat
```
You can see from the size of the resulting `data.frame` that we write a lot in this group!
Let's see over how much time we managed to accumulate `r scales::comma(nrow(chat))` messages.
I use a couple of extra packages for that:
```{r messages_over_time, message = FALSE, warning = FALSE}
library("ggplot2"); theme_set(theme_minimal())
library("lubridate")
chat %>%
mutate(day = date(time)) %>%
count(day) %>%
ggplot(aes(x = day, y = n)) +
geom_bar(stat = "identity") +
ylab("") + xlab("") +
ggtitle("Messages per day")
```
The chat has been going on for a while and on some days there were more than a hundred messages.
Who's responsible for all of this?
```{r echo = FALSE}
chat <- chat %>%
mutate(author = gsub("\\s.*", "", author)) # I remove the last names here for anonymity
```
```{r messages_per_author}
chat %>%
mutate(day = date(time)) %>%
count(author) %>%
ggplot(aes(x = reorder(author, n), y = n)) +
geom_bar(stat = "identity") +
ylab("") + xlab("") +
coord_flip() +
ggtitle("Number of messages")
```
Looks like we contributed more or less the same number of messages, with Erika slightly leading the field.
One thing that is always fun to do is finding out what people's favourite emojis are:
```{r emojis}
library("tidyr")
chat %>%
unnest(emoji) %>%
count(author, emoji, sort = TRUE) %>%
group_by(author) %>%
top_n(n = 6, n) %>%
ggplot(aes(x = reorder(emoji, n), y = n, fill = author)) +
geom_col(show.legend = FALSE) +
ylab("") +
xlab("") +
coord_flip() +
facet_wrap(~author, ncol = 2, scales = "free_y") +
ggtitle("Most often used emojis")
```
On some operating systems, the default font in `ggplot2` does not support emojis.
In this case you might want to move the emojis inside the plot instead.
I use emoji images from Twitter as they can be easily queried:
```{r emojis2}
library("ggimage")
emoji_data <- rwhatsapp::emojis %>% # data built into package
mutate(hex_runes1 = gsub("\\s.*", "", hex_runes)) %>% # ignore combined emojis
mutate(emoji_url = paste0("https://abs.twimg.com/emoji/v2/72x72/",
tolower(hex_runes1), ".png"))
chat %>%
unnest(emoji) %>%
count(author, emoji, sort = TRUE) %>%
group_by(author) %>%
top_n(n = 6, n) %>%
left_join(emoji_data, by = "emoji") %>%
ggplot(aes(x = reorder(emoji, n), y = n, fill = author)) +
geom_col(show.legend = FALSE) +
ylab("") +
xlab("") +
coord_flip() +
geom_image(aes(y = n + 20, image = emoji_url)) +
facet_wrap(~author, ncol = 2, scales = "free_y") +
ggtitle("Most often used emojis") +
theme(axis.text.y = element_blank(),
axis.ticks.y = element_blank())
```
Looks like we have a clear winner: all of us like the :joy: ("face with tears of joy") most.
:sweat_smile: ("grinning face with sweat") is also very popular, except with Erika who has a few more flamboyant favourites.
I apparently tend to use fewer emojis overall while Erika is leading the field (again).
(Note that the emojis are not ordered within the facets but by overall number of appearances, see next plot for a solution.)
How does it look if we compare favourite words?
I use the excellent `tidytext` package to get this task done^[Note that most of the analysis below is taken (or heavily inspired) from the book at [tidytextmining.com/](https://www.tidytextmining.com/) where you can also learn much more about text analysis.]:
```{r often_used_words}
library("tidytext")
chat %>%
unnest_tokens(input = text,
output = word) %>%
count(author, word, sort = TRUE) %>%
group_by(author) %>%
top_n(n = 6, n) %>%
ggplot(aes(x = reorder_within(word, n, author), y = n, fill = author)) +
geom_col(show.legend = FALSE) +
ylab("") +
xlab("") +
coord_flip() +
facet_wrap(~author, ncol = 2, scales = "free_y") +
scale_x_reordered() +
ggtitle("Most often used words")
```
This doesn't make much sense.
First of all, because we write in German which you might not understand :wink:.
But it also looks weird that Artur and Erika seem to often use the words "media" and "omitted".
Of course, this is just the placeholder WhatsApp puts into the log file instead of a picture or video.
But the other words don't look particularly useful either.
They are what's commonly called stopwords: words that are used often but don't carry any substantial meaning.
"und" for example is simply "and" in English.
"der", "die" and "das" all mean "the" in English (which makes German pure joy to learn for an English native speaker :sweat_smile:).
To get around this mess, I remove these words before making the plot again:
```{r often_used_words_clean}
library("stopwords")
to_remove <- c(stopwords(language = "de"),
"media",
"omitted",
"ref",
"dass",
"schon",
"mal",
"android.s.wt")
chat %>%
unnest_tokens(input = text,
output = word) %>%
filter(!word %in% to_remove) %>%
count(author, word, sort = TRUE) %>%
group_by(author) %>%
top_n(n = 6, n) %>%
ggplot(aes(x = reorder_within(word, n, author), y = n, fill = author)) +
geom_col(show.legend = FALSE) +
ylab("") +
xlab("") +
coord_flip() +
facet_wrap(~author, ncol = 2, scales = "free_y") +
scale_x_reordered() +
ggtitle("Most often used words")
```
Still not very informative, but hey, this is just a private conversation, what did you expect?
It seems though that we agree with each other a lot, as "ja" (yes) and ok are among the top words for all of us.
The antonym "ne" (nope) is far less common and only on Artur's and Erika's top lists.
I seem to send a lot of links as both "https" and "ref" appear on my top list.
Alexandra is talking to or about Erika and me pretty often and Artur is the only one who mentions "euro" (as in the currency) pretty often.
Another way to determine favourite words is to calculate the term frequency–inverse document frequency (tf–idf).
Basically, what the measure does, in this case, is to find words that are common within the messages of one author but uncommon in the rest of the messages.
```{r Important_words}
chat %>%
unnest_tokens(input = text,
output = word) %>%
select(word, author) %>%
filter(!word %in% to_remove) %>%
mutate(word = gsub(".com", "", word)) %>%
mutate(word = gsub("^gag", "9gag", word)) %>%
count(author, word, sort = TRUE) %>%
bind_tf_idf(term = word, document = author, n = n) %>%
filter(n > 10) %>%
group_by(author) %>%
top_n(n = 6, tf_idf) %>%
ggplot(aes(x = reorder_within(word, n, author), y = n, fill = author)) +
geom_col(show.legend = FALSE) +
ylab("") +
xlab("") +
coord_flip() +
facet_wrap(~author, ncol = 2, scales = "free_y") +
scale_x_reordered() +
ggtitle("Important words using tf–idf by author")
```
Now the picture changes pretty much entirely.
First, the top words of the different authors have very little overlap now compared to before---only exceptions being 9gag (platform to share memes) in Alexandra's and my messages and "grade" (now) which Artur and I use.
This is due to the tf–idf measure which tries to find only words specific to an author.
Now instead of Erika and me, Alexandra talks about Artur, something only she does.
Artur is the only one to talk about a Macbook (as he is the only one who owns one).
Erika seems to thrive on abbreviations like "oman" (abbreviation for "Oh Mann"/"oh man", not the country) "eig" ("eigentlich"/actually) "joh" (abbreviation for my name) and curiously "jaa", which is "ja" (yes) with and unnecessary extra "a".
I show that my favourite adjective is "super" and that I talked about a processor at some point for some reason.
Another common text mining tool is to calculate lexical diversity.
Basically, you just check how many unique words are used by an author.
```{r Lexical_Diversity, message=FALSE}
chat %>%
unnest_tokens(input = text,
output = word) %>%
filter(!word %in% to_remove) %>%
group_by(author) %>%
summarise(lex_diversity = n_distinct(word)) %>%
arrange(desc(lex_diversity)) %>%
ggplot(aes(x = reorder(author, lex_diversity),
y = lex_diversity,
fill = author)) +
geom_col(show.legend = FALSE) +
scale_y_continuous(expand = (mult = c(0, 0, 0, 500))) +
geom_text(aes(label = scales::comma(lex_diversity)), hjust = -0.1) +
ylab("unique words") +
xlab("") +
ggtitle("Lexical Diversity") +
coord_flip()
```
It appears that I use the most unique words, even though Erika wrote more messages overall.
Is this because I use some amazing and unique technical terms?
Let's find out:
```{r unique_johannes}
o_words <- chat %>%
unnest_tokens(input = text,
output = word) %>%
filter(author != "Johannes") %>%
count(word, sort = TRUE)
chat %>%
unnest_tokens(input = text,
output = word) %>%
filter(author == "Johannes") %>%
count(word, sort = TRUE) %>%
filter(!word %in% o_words$word) %>% # only select words nobody else uses
top_n(n = 6, n) %>%
ggplot(aes(x = reorder(word, n), y = n)) +
geom_col(show.legend = FALSE) +
ylab("") + xlab("") +
coord_flip() +
ggtitle("Unique words of Johannes")
```
Looking at the top words that are only used by me we see these are words I don't use very often either.
There are two technical terms here: "prozessor" and "webseite" which kind of make sense.
I'm also apparently the only one to share links to the German news site zeit.de.
The English "i'm" is in there because autocorrect on my phone tends to change the German word "im" (in).
Overall, WhatsApp data is just a fun source to play around with text mining methods.
But if you have more serious data, a proper text analysis is also possible, just like with other social media data.
---