1Rtweets <- function(n=25, lang=NULL, since=NULL, ...) {
2    searchTwitter("#rstats", n=n, lang=lang, since=since, ...)
3}
4
5searchTwitter <- function(searchString, n=25, lang=NULL,
6                          since=NULL, until=NULL, locale=NULL,
7                          geocode=NULL, sinceID=NULL, maxID=NULL,
8                          resultType=NULL,
9                          retryOnRateLimit=120, ...) {
10
11
12  if (nchar(searchString) > 1000) {
13    stop("searchString can only be up to 1000 characters")
14  }
15
16  if (n <= 0)
17        stop("n must be positive")
18    n <- as.integer(n)
19
20  if (is.null(since)) {
21    since_date = NULL
22  } else {
23    since_date = strsplit(since, " ")[[1]][1]
24  }
25  if (is.null(until)) {
26    until_date = NULL
27  } else {
28    until_date = strsplit(until, " ")[[1]][1]
29    if (until_date == since_date) {
30      ## If since & until are on the same day nothing will be returned. Move
31      ## until up a day and then we'll filter this later
32      until_date = as.Date(since_date) + 1
33    }
34  }
35
36  if (!is.null(geocode)) {
37    geocheck = strsplit(geocode[[1]], ',')[[1]]
38    lat = as.numeric(geocheck[1])
39    lon = as.numeric(geocheck[2])
40    if ((lon > 180) || (lon < -180)) {
41      stop('Longitude need to be in range [180,-180].')
42    }
43    if ((lat > 90)||(lat < -90)) {
44      stop('Latitude need to be in range [90.0,-90.0].')
45    }
46  }
47
48  params <- buildCommonArgs(lang=lang, locale=locale, since=since_date, until=until_date,
49                            geocode=geocode, since_id=sinceID, max_id=maxID,
50                            result_type=resultType )
51  params[['q']] <- searchString
52  params[["include_entities"]] = TRUE
53
54  jsonList <- doRppAPICall("search/tweets", n, params=params, retryOnRateLimit=retryOnRateLimit, ...)
55  statuses = import_statuses(jsonList)
56
57  datetimes = sapply(statuses, function(x) x$getCreated())
58  if (is.null(since)) {
59    since_statuses = seq_along(statuses)
60  } else {
61    since_statuses = which(datetimes >= as.numeric(as.POSIXct(since, tz="UTC")))
62  }
63  if (is.null(until)) {
64    until_statuses = seq_along(statuses)
65  } else {
66    until_statuses = which(datetimes <= as.numeric(as.POSIXct(until, tz="UTC")))
67  }
68  good_statuses = intersect(since_statuses, until_statuses)
69  return(statuses[good_statuses])
70}
71
72## I don't know how many times I've typod this, making an alias
73searchTwitteR = searchTwitter
74