forked from benmarwick/AAA2011-Tweets
-
Notifications
You must be signed in to change notification settings - Fork 20
/
utilities.R
54 lines (39 loc) · 1.09 KB
/
utilities.R
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
# Utilities for this package
EnsurePackage <- function(x) {
# EnsurePackage(x) - Installs and loads a package if necessary
# Args:
# x: name of package
x <- as.character(x)
if (!require(x, character.only=TRUE)) {
install.packages(pkgs=x, repos="http://cran.r-project.org")
require(x, character.only=TRUE)
}
}
TrimAt <- function(x) {
# remove @ from text
sub('@', '', x)
}
TrimHead <- function(x) {
# remove starting @, .@, RT @, MT @, etc.
sub('^(.*)?@', '', x)
}
TrimUsers <- function(x) {
# remove users, i.e. "@user", in a tweet
str_replace_all(x, '(@[[:alnum:]_]*)', '')
}
TrimHashtags <- function(x) {
# remove hashtags, i.e. "#tag", in a tweet
str_replace_all(x, '(#[[:alnum:]_]*)', '')
}
TrimUrls <- function(x) {
# remove urls in a tweet
str_replace_all(x, 'http[^[:blank:]]+', '')
}
TrimOddChar <- function(x) {
# remove odd charactors
iconv(x, to = 'UTF-8')
}
CosineSimilarity <- function(va, vb) {
# Computer cosine similarity between two numeric vectors of the same length
crossprod(va, vb) / sqrt(crossprod(va) * crossprod(vb))
}