This repository has been archived by the owner on Sep 18, 2019. It is now read-only.
/
block027_regular-expressions.Rmd
300 lines (220 loc) · 9.65 KB
/
block027_regular-expressions.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
---
title: "Regular Expressions and Character Data"
author: "Kieran Samuk"
date: "October 27, 2015"
output: html_document
---
Hopefully we now all have a nice grasp of regular expressions. Now, lets wield the mighty hammer of regex to wrangle some unruly text data in R!
### Set up
Install `stringr` if you don't have it already!
```{r message=FALSE}
#install.packages("stringr")
library("stringr")
library("dplyr")
library("ggplot2")
```
## Part 1: Basic string manipluation in R
### `nchar` - count the length of individual strings.
```{r}
test_str <- c("STAT545 is great!", "Wooooo!")
nchar(test_str)
```
### `substr` - extract or replace substrings in a character vector.
Lets extract the 1st through 7th elements:
```{r}
substr(test_str, 1, 7)
```
Now lets replace the 1st through 7th elements with SCIENCE:
```{r}
substr(test_str, 1, 7) <- "SCIENCE"
test_str
```
### `paste` - concatenate or combine strings
This is a weirdly complex function, so let's just touch on the common uses. The 'sep' parameter determines the separating character (defaults to a single space).
```{r}
paste("abc", "efg")
paste("abc", "efg", sep = "")
```
`paste0` is a shortcut for `paste(..., sep = "")`
```{r}
paste0("abc", "efg")
```
If you want to combined many multi-value vectors, you need to also specify "collapse":
```{r}
paste(c("abc", "efg"), c("hij", "klm"), sep = "", collapse = "")
```
### `strsplit` - split a string into a list of substrings
For example, we can split a vector based on commas:
```{r}
x <- c("abc,cbe", "cb,gb,aaa")
strsplit(x, split = ",")
```
Remember this returns a list, so treat it like one! Perhaps we want every second element:
```{r}
strsplit(x, split = ",") %>% lapply(function(x) x[2])
```
### Part 2: Regex in R
You now know the basics of wrangling character data in R! You are great. Now lets see how we can use these skills along with regex to do some very powerful manipulations.
#### Quick notes on Regex in R
1. The character classes **\\w**, **\\d**, **\\s**, can also be referred to using POSIX classes in R. They are identical in function, but some people consider these more readable. You can see all of them by typing `?regex`. Some examples:
* **\\w** = [[:alnum:]]
* **\\d** = [[:digit:]]
* **\\s** = [[:space:]]
2. When escaping special characters or using character classes, you often (always?) need to **double** escape them, e.g. **\\\\w** instead of **\\w**
### Load the `news_tweets`
For this exercise, lets load a data set of tweets in the last week from four news sources (CBC, CNN, Al Jazeera, Reuters). I gathered these using the R package `twitteR`, which interfaces with Twitter's REST API.
```{r}
news_tweets <- read.delim("https://www.dropbox.com/s/cbgcpkizun51wbk/news_tweets.txt?dl=1", header = TRUE, stringsAsFactors = FALSE, sep = "\t", quote = "", allowEscapes = TRUE)
glimpse(news_tweets)
```
* `user_name` = twitter user name (shortened)
* `created` = date tweeted
* `retweets` = number of retweets to date
* `text` = the raw text of the tweet
### `grep` - find a pattern in a character vector
A very basic task you might want to do is search for a regular expression in a character vector.
`grep` takes a regular expression and a character vector as input, and returns the *indexes* of the matches.
Lets use a regular expression to find tweets in `news_tweets` that contain hashtags. A hash tag is a '#' followed by one or more alphanumeric character, e.g. #rstats, #Canada, etc.
```{r}
# two identical ways of writing this regex:
hastag_pattern <- "#\\w+"
hastag_pattern <- "#[[:alnum:]]+"
grep(hastag_pattern, news_tweets$text)
```
Setting `value = TRUE` returns the *actual value* of the vector at those indexes:
```{r}
grep(hastag_pattern, news_tweets$text, value = TRUE) %>% head(n = 5)
```
We can also invert the search using `invert = TRUE`:
```{r}
grep(hastag_pattern, news_tweets$text, value = TRUE, invert = TRUE) %>% head(n = 5)
```
### `grepl` - logical pattern matching
`grepl` (grep logical) is similar to `grep`, but returns TRUE or FALSE for every element of the vector:
```{r}
hastag_pattern <- "#[[:alnum:]]+"
grepl(hastag_pattern, news_tweets$text) %>% head(n = 10)
```
You can use `grepl` with `filter` from `dplyr` to filter rows based on a regular expression. Lets filter for tweets that contain urls:
```{r tidy=FALSE}
# url regex
url_pattern <- "http[s]?://[^ ]+"
# filter news tweets using grepl
hashtag_tweets <- news_tweets %>%
filter(grepl(url_pattern, news_tweets$text))
# print the first 6 rows of the resulting data frame
head(hashtag_tweets)
```
### `gsub` - find and replace
Another basic task is matching a regular expression and replacing the matches with a specific string.
`gsub` takes a regular expression, a replacement string, and a character vector. It returns a character vector with **all** instances of the regex replaced by the replacement string.
A common use of `gsub` is 'cleaning' text. For example, lets remove away all the urls from our tweets:
```{r highlight=TRUE}
# reminder of what a tweet looks like
news_tweets$text[20]
# the url regex
url_pattern <- "http[s]?://[[:alnum:].\\/]+"
# replace all matches to the above regex with nothing ""
clean_tweets <- gsub(pattern = url_pattern, replacement = "", news_tweets$text)
clean_tweets[20]
```
We can also used `gsub` to clean off extra or trailing white space:
```{r highlight=TRUE}
# regex for removing double OR trailing spaces
trailing_space <- "[ ]{2,}|[ ]+$"
clean_tweets <- gsub(pattern = trailing_space, replacement = "", clean_tweets)
# a clean tweet!
clean_tweets[20]
```
To conclude this section, lets replace all instances of words beginning with "polit" with "balloons".
First, the (cleaned) tweets that contain our pattern of interest:
```{r highlight=TRUE}
poli_pattern <- "[Pp]olit[[:alnum:]]+"
poli_pattern %>% grep(clean_tweets, value = TRUE)
```
We now have the tools to make this way better:
```{r highlight=TRUE}
poli_pattern %>% gsub(replacement = "balloons", clean_tweets) %>% grep("balloons", ., value = TRUE)
```
### Part 3: The `stringr` package
Like all things in R, Hadley Wickham has tried to improve string handling. This is implemented in his package `stringr`. There are lots of functions that take the place of existing ones, but with nicer syntax. Lets use it along with `dplyr` to do a basic lexical analysis of our tweet-set!
For starters, lets clean out all the "non-word" text from the tweets. Lets clean out:
* URLs: `http[s]?://[[:alnum:].\\/]+`
* Twitter user names (@CNN, etc.): `@[\\w]*`
* Hashtags (#rstats): `#[\\w]*"`
* Possessives ('s): `'s`
* Weird Unicode stuff/html tags (e.g. <U008+>): `<.*>`
First, make regex for each thing we want to remove, then combined them together with "|"'s (remember, this means "or" in regex):
```{r}
stuff_to_remove <- c("http[s]?://[[:alnum:].\\/]+", "@[\\w]*", "#[\\w]*", "<.*>", "'s")
stuff_to_remove <- paste(stuff_to_remove, sep = "|", collapse="|")
```
Next, lets use `str_replace_all` (like `gsub`) to scrub this puppy down:
```{r}
clean_tweets <- str_replace_all(news_tweets$text, stuff_to_remove, "")
clean_tweets[20:25]
```
Nice, but it has gross trailing white space! Luckily, `stringr` has a function specifically for this task. `str_trim` removes leading and trailing white space:
```{r}
clean_tweets <- str_trim(clean_tweets)
clean_tweets[20:25]
```
That feels good. Next, lets extract all the words from the whole data set using `str_extract_all` (like `grep(...,value = TRUE)`)
```{r}
tweet_words <- str_extract_all(clean_tweets, "[A-Za-z]+")
head(tweet_words)
```
OK! So what are the top, say, fifteen words?
```{r}
word_counts <- unlist(tweet_words) %>% table %>% data.frame
names(word_counts) <- c("word", "count")
word_counts %>%
arrange(count) %>%
top_n(15)
```
Hmm. Those are kind of boring. Lets change the regex to catch words that start with a capital letter, and are at least 4 letters long.
```{r warning=FALSE,message=FALSE}
tweet_words <- str_extract_all(clean_tweets, "[A-Z][a-z]{4,}")
word_counts <- unlist(tweet_words) %>% table %>% data.frame
names(word_counts) <- c("word", "count")
word_counts %>%
top_n(25)%>%
arrange(count)
```
This feels like we are winning. Now for some fun: a word cloud.
```{r warning=FALSE, message=FALSE}
#install.packages("wordcloud")
#install.packages("wesanderson")
library("wordcloud")
library("wesanderson")
pal <- wes_palette(name = "Zissou", 51, type ="continuous") %>% as.character()
word_counts %>%
top_n(50) %>%
with(wordcloud(word, count, ordered.colors = TRUE, color = pal, use.r.layout = TRUE))
```
We could also break it up by agency:
```{r warning=FALSE,message=FALSE}
news_clean_tweets <- news_tweets
news_clean_tweets$text <- clean_tweets
words_df <- news_clean_tweets %>%
group_by(user_name) %>%
do(words = str_extract_all(.$text, "[A-Z][a-z]{4,}"))
par(mfrow = c(2,2))
for (i in 1:4){
word_counts <- unlist(words_df[i, 2]) %>% table %>% data.frame
names(word_counts) <- c("word", "count")
word_counts %>%
top_n(50) %>%
with(wordcloud(word, count, ordered.colors = TRUE,
color = wes_palette(name = "Zissou", nrow(.), type ="continuous"),
scale = c(3.5, 0.15)))
text(0, 0.9, words_df$user_name[i], cex = 1.5, adj = c(0, 0))
}
```
### That's it!
You hopefully now have a grasp of regular expressions and the basic tools of text processing in R. There is much more to learn, but I hope this introduction gets you off on the right foot.
### Further Reading
* [The stringr vignette](https://cran.r-project.org/web/packages/stringr/vignettes/stringr.html)
* [Last year's lesson by Gloria Li](https://stat545-ubc.github.io/block022_regular-expression.html)
* [CRAN Task View: Natural Language Processing](https://cran.r-project.org/web/views/NaturalLanguageProcessing.html)
* [Regular expressions in R](https://www.youtube.com/watch?v=q8SzNKib5-4)