├── .gitignore ├── DESCRIPTION ├── LICENSE ├── NAMESPACE ├── R ├── authentification.R ├── dateOperation.R ├── filterstream.R ├── geoLocation.R ├── hometimeline.R ├── mongoConnection.R ├── mongoQueries.R └── regexBuilder.R ├── README.md ├── inst └── doc │ ├── TwitteR2Mongo.R │ ├── TwitteR2Mongo.Rmd │ └── TwitteR2Mongo.html ├── man ├── absoluteHashtagCount.Rd ├── buildRegexQuery.Rd ├── cleanTwitterTimeline.Rd ├── connect2MongoDb.Rd ├── createIntervalVector.Rd ├── createTwitterTimeSeries.Rd ├── createTwitterTimeline.Rd ├── defaultThreshold.Rd ├── drawMap.Rd ├── extractCoordinates.Rd ├── fieldValuePair.Rd ├── geocodeDataFrame.Rd ├── getInterval.Rd ├── getMongoFields.Rd ├── import2mongo.Rd ├── makeOAuth.Rd ├── operatorValuePair.Rd ├── plotTweets.Rd ├── rankTweets.Rd ├── setAPICredentials.Rd ├── setMongoDbCredentials.Rd ├── startStreaming.Rd ├── stopStreaming.Rd ├── streamingLoop.Rd ├── topHashtagsInInterval.Rd ├── updateHometimeline.Rd └── useConjunction.Rd └── vignettes ├── TwitteR2Mongo.Rmd └── figure ├── Density.png └── Timeline.png /.gitignore: -------------------------------------------------------------------------------- 1 | locationscache.Rda 2 | .httr-oauth 3 | *.txt 4 | *.Rproj 5 | *.Rbuildignore 6 | lock_file 7 | *.Rhistory 8 | /.Rproj.user/ -------------------------------------------------------------------------------- /DESCRIPTION: -------------------------------------------------------------------------------- 1 | Package: TwitteR2Mongo 2 | Type: Package 3 | Title: Stream Tweets form Twitter-API to MongoDB based on trend detection 4 | Version: 0.5.2 5 | Date: 2016-01-14 6 | Author: Philipp Prettel and Lion Weber 7 | Maintainer: Philipp Prettel 8 | Description: The package retrives the hometimeline of the user and evaluates 9 | those. The most common hashtags of the hometimeline, are used to stream all 10 | tweets containing these results. 11 | License: GPL-2 12 | LazyData: TRUE 13 | Suggests: 14 | knitr, 15 | rmarkdown 16 | Depends: 17 | stringr, 18 | ggmap, 19 | ggplot2, 20 | maps, 21 | base64enc 22 | Imports: 23 | jsonlite, 24 | mongolite, 25 | httr 26 | VignetteBuilder: knitr 27 | RoxygenNote: 5.0.1 28 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | {one line to give the program's name and a brief idea of what it does.} 635 | Copyright (C) {year} {name of author} 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | {project} Copyright (C) {year} {fullname} 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | -------------------------------------------------------------------------------- /NAMESPACE: -------------------------------------------------------------------------------- 1 | # Generated by roxygen2: do not edit by hand 2 | 3 | export(absoluteHashtagCount) 4 | export(buildRegexQuery) 5 | export(cleanTwitterTimeline) 6 | export(connect2MongoDb) 7 | export(createIntervalVector) 8 | export(createTwitterTimeSeries) 9 | export(createTwitterTimeline) 10 | export(defaultThreshold) 11 | export(drawMap) 12 | export(extractCoordinates) 13 | export(fieldValuePair) 14 | export(geocodeDataFrame) 15 | export(getInterval) 16 | export(getMongoFields) 17 | export(import2mongo) 18 | export(makeOAuth) 19 | export(operatorValuePair) 20 | export(plotTweets) 21 | export(rankTweets) 22 | export(setAPICredentials) 23 | export(setMongoDbCredentials) 24 | export(startStreaming) 25 | export(stopStreaming) 26 | export(streamingLoop) 27 | export(topHashtagsInInterval) 28 | export(updateHometimeline) 29 | export(useConjunction) 30 | import(ggmap) 31 | import(ggplot2) 32 | import(maps) 33 | import(mongolite) 34 | import(stringr) 35 | -------------------------------------------------------------------------------- /R/authentification.R: -------------------------------------------------------------------------------- 1 | 2 | 3 | #' Store Twitter-API Credentials 4 | #' 5 | #' This function stores you Twitter-API key and secret to make it available for other functions and 6 | #' for other instances of R. 7 | #' 8 | #' @param key The key for the Twitter-API: Consumer Key (API Key) 9 | #' @param secret The scret for the Twitter-API: Consumer Secret (API Secret) 10 | #' 11 | #' @return None 12 | #' 13 | #' @examples 14 | #' setAPICredentials(key = "Consumer Key", secret = "Consumer Secret") 15 | #' 16 | #' @export 17 | 18 | setAPICredentials <- function(key, secret) { 19 | if ((!class(key) == "character") || 20 | (!class(secret) == "character")) { 21 | stop("Key and sectet must be character") 22 | } 23 | Sys.setenv(twitter_key = key) 24 | Sys.setenv(twitter_secret = secret) 25 | message("Credentials stored, make sure to set callback url to http://127.0.0.1:1410") 26 | } 27 | 28 | #' Make OAuth 29 | #' 30 | #' Creates oAuth token for Twitter-API Access and returns token 31 | #' 32 | #' @param key The key for the Twitter-API (character) 33 | #' @param secret The scret for the Twitter-API (character) 34 | #' 35 | #' @return OAuth token 36 | #' 37 | #' @examples 38 | #' #makeOAuth() 39 | #' 40 | #' @export 41 | #' 42 | 43 | makeOAuth <- 44 | function(key = Sys.getenv("twitter_key"), secret = Sys.getenv("twitter_secret")) { 45 | # Generate or load authetification token, please store the credentials 46 | 47 | if ((key == "") || (secret == "")) { 48 | stop("Twitter key or secret are not set properly, use setAPICredentials to fix this.") 49 | } 50 | myapp <- httr::oauth_app("twitter", key = key, secret = secret) 51 | return (httr::oauth1.0_token(httr::oauth_endpoints("twitter"), myapp)) 52 | } 53 | -------------------------------------------------------------------------------- /R/dateOperation.R: -------------------------------------------------------------------------------- 1 | #' Top Hashtags in intervall 2 | #' 3 | #' Retrives the most used hashtags in a given time interval 4 | #' 5 | #' @param mongo a mongoDB connection to use (default: hometimeline) 6 | #' @param interval a time interval which can be generated by \link{getInterval} needs to be in unix timestamp format 7 | #' @param amount limits the number of hashtags returned 8 | #' 9 | #' @return list of hashtags 10 | #' 11 | #' @examples 12 | #' #topHashtagsInInterval(hometimeline, interval = getInterval(60*24), 10) 13 | #' #or alternatively specify interval beforehand 14 | #' #timeframe <- c("2016-01-04 18:37:43 CET","2016-01-05 18:37:43 CET") 15 | #' #hashtags <- topHashtagsInInterval(hometimeline, interval = 16 | #' #getInterval(inputinterval = timeframe), 10) 17 | #' 18 | #' @export 19 | topHashtagsInInterval <- function(mongo, interval, amount = 10){ 20 | # interval -> first element is the starting point of the interval, i.e. the earlier timepoint 21 | # second element is the end of the interval, i.e. the later timepoint 22 | # limiting operator within the query somehow did not work anymore 23 | # so placed the amount parameter at the end of the fctn. 24 | 25 | basequery <- '[{"$unwind": "$entities.hashtags"}, 26 | {"$match": {"timestamp_ms": {"$gte": "starttime" , "$lte": "endtime" }}}, 27 | {"$project": {"entities.hashtags": {"$toLower": "$entities.hashtags.text"}}}, 28 | {"$group": {"_id":"$entities.hashtags", "count":{"$sum":1}}}, 29 | {"$sort": {"count":-1}}, 30 | {"$limit": amount}]' 31 | query <- str_replace_all(str_c(basequery), c("starttime"=interval[1], 32 | "endtime"=interval[2], 33 | "amount"= amount)) 34 | hashtags <- mongo$aggregate(query) 35 | if( length(hashtags)==0) { 36 | return(hashtags) 37 | } 38 | return(hashtags) 39 | } 40 | 41 | #' Get Interval 42 | #' 43 | #' Calculates an intervall from now-decrease until now. Twitter uses GMT therefore 44 | #' the supplied time can be modifed by adjust, default is for German daylight saving time. 45 | #' Alternatively an interval may be provided and the corresponding unix timestamps will 46 | #' be returned. Set Sys.setlocale("LC_TIME", "English") in order 47 | #' to be able to correctly process the twitter timestamp. Avoid timestamps with the 48 | #' times 00:00:00 and 12:00:00 since they are a digit short. 49 | #' 50 | #' @param decrease size of interval (in minutes) 51 | #' @param adjust time to subtract from system time to get GMT (in minutes) 52 | #' @param inputinterval alternatively input a time interval 53 | #' 54 | #' @return interval 55 | #' 56 | #' @examples 57 | #' #Get an interval covering the last 24 hours 58 | #' getInterval(60*24) 59 | #' 60 | #' #Get an interval covering the last hour 61 | #' getInterval() 62 | #' 63 | #' #Specify interval and get corresponding unix timestamps 64 | #' #isodate <- c("2016-01-04 18:37:43","2016-01-05 18:37:43") 65 | #' #getInterval(inputinterval = isodate) 66 | #' 67 | #' #twitter <- c("Tue Jan 05 12:51:00 +0000 2016","Tue Jan 05 16:51:00 +0000 2016") 68 | #' #twitter <- getInterval(inputinterval = twitter) 69 | #' 70 | #' @export 71 | getInterval <- function(decrease = 60, adjust = 0, inputinterval) { 72 | # calculates the time interval by the specified amount of the decrease parameter in minutes 73 | # standard is 60 minutes. 74 | if (missing(inputinterval) == TRUE) { 75 | time <- as.numeric(Sys.time()) * 1000 - adjust 76 | interval <- c(time - decrease * 60000, time) 77 | } 78 | 79 | else { 80 | if (all(grepl(pattern = "^\\d{4}-\\d{2}-\\d{2} \\d{2}:\\d{2}:\\d{2}", x = inputinterval)) == 81 | TRUE) { 82 | interval <- 83 | as.numeric(as.POSIXct(inputinterval, format = "%Y-%m-%d %T")) * 1000 84 | } 85 | 86 | else if (all( 87 | grepl(pattern = "^\\w{3} \\w{3} \\d{2} \\d{2}:\\d{2}:\\d{2} \\+\\d{4} \\d{4}", x = inputinterval) 88 | ) == TRUE) { 89 | interval <- 90 | as.numeric(as.POSIXct(inputinterval, tz = "GMT", format = "%a %b %d %H:%M:%S %z %Y")) * 91 | 1000 - ceiling(as.numeric(difftime( 92 | as.POSIXlt(Sys.time(), Sys.timezone()),as.POSIXlt(Sys.time(), tz = "GMT"),tz = "", units = "secs" 93 | ))) * 1000 94 | } 95 | else { 96 | message("Wrong interval format. Use YYYY-MM-DD HH:MM:SS or the Twitter date format.") 97 | } 98 | } 99 | return(floor(interval)) 100 | } 101 | 102 | # Helper function to merge top hashtags from different time intervalls to one list 103 | # Will NOT be exported, used by streamingLoop 104 | mergeHashtagFrames<- function (frame1,frame2) { 105 | if(length(frame1)==0) { 106 | return(frame2) 107 | } 108 | else if(length(frame2)==0) { 109 | return(frame1) 110 | } 111 | else { 112 | hashtags <- unique(rbind.data.frame(frame1,frame2)) 113 | return(hashtags) 114 | } 115 | } 116 | 117 | # Converts date of the form YYYY-mm-dd HH:MM:SS to a unixtimestamp in ms 118 | userToTimestamp <- function(data) { 119 | 120 | data <- as.numeric(as.POSIXct(data, format = "%Y-%m-%d %T"))*1000 121 | return(data) 122 | } 123 | 124 | # Converts unixtimestamps to userdate of the form yyyy-mm-dd hh:mm:ss 125 | timestampToUserdate <- function(data) { 126 | 127 | if(is.numeric(data) == TRUE) { 128 | 129 | if(all(nchar(data, type="chars")==13)) { 130 | data <- as.POSIXct(data/1000, origin = "1970-01-01 00:00:00") 131 | } 132 | 133 | else if(all(nchar(data, type="chars")==10)) { 134 | data <- as.POSIXct(data, origin = "1970-01-01 00:00:00") 135 | } 136 | 137 | else { 138 | stop("Timestamp is incorrect. Timestamps need equal lengths in order to be converted.") 139 | } 140 | } 141 | else { 142 | stop("Data is not numeric.") 143 | } 144 | return(data) 145 | } 146 | 147 | # Converts Twitterdate of the Form "Fri Nov 13 12:56:04 +0000 2015" to unixtimestamp in ms 148 | twitterToTimestamp <- function(data) { 149 | 150 | data <- as.numeric(as.POSIXct(data, format ="%a %b %d %H:%M:%S %z %Y"))*1000 151 | return(data) 152 | } 153 | 154 | -------------------------------------------------------------------------------- /R/filterstream.R: -------------------------------------------------------------------------------- 1 | #' Importing a filterstream file to mongoDB. 2 | #' 3 | #' Used to import fiterstream files to mongo 4 | #' in a seperate R process. Can be used to import tweets 5 | #' manually for times of MongoDB downtime. The file to import 6 | #' must be located in the directory set in sys.setenv("wd" =) 7 | #' 8 | #' @param fileid Nnumber of the file to import 9 | #' @param connection A mongo db connection 10 | #' @param createLog If set to FALSE output is send to the 11 | #' console instead of the logfile (logfile_import.txt) 12 | #' 13 | #' @return none 14 | #' 15 | #' @examples 16 | #' #import2mongo(2) 17 | #' 18 | #' @export 19 | import2mongo <- 20 | function(fileid, connection = "filterstream", createLog = TRUE) { 21 | if (createLog == TRUE) { 22 | logfile <- file("logfile_import.txt","at") 23 | sink( 24 | logfile, append = TRUE, type = c("message"), split = FALSE 25 | ) 26 | message(toString(Sys.time()), " Starting import of file no. ", fileid) 27 | } 28 | mconnection <- connect2MongoDb(connection) 29 | setwd(Sys.getenv("wd")) 30 | filename <- paste0(connection, fileid, ".json") 31 | con_imp <- file(filename,"r") 32 | amount <- try(mconnection$import(con_imp, bson = FALSE)) 33 | close(con_imp) 34 | unlink(filename) 35 | message(toString(Sys.time()), " Import completed! Processed ", amount, " tweets.") 36 | mconnection$remove('{"id_str":null}',multiple = TRUE) 37 | } 38 | 39 | 40 | #' Start streaming 41 | #' 42 | #' Start the streaming process for the filterstream 43 | #' in a seperate R process. The timeout also defines the maximum waiting time 44 | #' between executing \link{stopStreaming} and the end of the streaming process 45 | #' If no query_url is supplied then the topHashtags from the users hometimeline 46 | #' are used. 47 | #' 48 | #' @param timeout period of time after which the stream ist stopped 49 | #' and restarted with a updated list of search parameters 50 | #' @param query_url set a specific URL to query the API 51 | #' 52 | #' @return list of hashtags 53 | #' 54 | #' @examples 55 | #' #startStreaming(320) 56 | #' #startStreaming(60,"https://stream.twitter.com/1.1/statuses/filter.json?track=Trump") 57 | #' 58 | #' @export 59 | #' 60 | startStreaming <- function(timeout = 60, query_url) { 61 | Sys.setenv(wd = getwd()) 62 | clearLogfiles() 63 | # Check database and credentials to make sure streamingLoop has all required information. 64 | mconection <- connect2MongoDb("filterstream") 65 | mconection <- connect2MongoDb("hometimeline") 66 | tryCatch({ 67 | makeOAuth() 68 | }, error = function(e) { 69 | stop("Failed to create oAuth token. Check API credentials") 70 | }) 71 | 72 | if (missing(query_url)) { 73 | print("Now starting stream based on the hashtags of the supplied users network") 74 | command <- 75 | paste0( 76 | "Rscript -e library(TwitteR2Mongo);streamingLoop(",timeout,",", as.character(1),")" 77 | ) 78 | } 79 | 80 | else { 81 | Sys.setenv(query_url = query_url) 82 | print("Now starting stream based on supplied query_url") 83 | 84 | command <- 85 | paste0( 86 | "Rscript -e library(TwitteR2Mongo);streamingLoop(",timeout,",", as.character(2),")" 87 | ) 88 | } 89 | system(command = command, wait = FALSE) 90 | } 91 | 92 | 93 | #' Stop streaming 94 | #' 95 | #' Stop the streaming process. Streaming is stoped within the timeframe given 96 | #' as timeout in \link{startStreaming} 97 | #' Stop stream will not terminate the streaming process imediately but stop instead 98 | # of reloading if the timeout occurs. 99 | #' 100 | #' @return list of hashtags 101 | #' 102 | #' @examples 103 | #' #stopStreaming() 104 | #' 105 | #' @export 106 | 107 | stopStreaming <- function() { 108 | status <- file("stop_request.txt","w+b") 109 | writeLines("TRUE", status) 110 | close(status) 111 | } 112 | 113 | #' StreamingLoop 114 | #' 115 | #' StreamingLoop is usually started by \link{startStreaming} in a seperate instance of R. 116 | #' If you start StreamingLoop manually, you will not be able to stop it using R. StreamingLoop 117 | #' can be triggered to stop after timeout using \link{stopStreaming}. 118 | #' 119 | #' @param timeout Time until the streaming is stoped and restarted with updated parameters 120 | #' @param type The type of stream which is started. (1=Based on hometimeline) (2=Based on query_url) 121 | #' @param createLog If set to FALSE output is send to the console instead of the logfile 122 | #' (logfile_filterstream.txt) 123 | #' 124 | #' @examples 125 | #' #do not run 126 | #' #streamingLoop() 127 | #' 128 | #' @export 129 | streamingLoop <- function(timeout = 30, type, createLog = TRUE) { 130 | if (createLog == TRUE) { 131 | logfile <- file("logfile_filterstream.txt","at") 132 | sink( 133 | logfile, append = TRUE, type = c("message"), split = FALSE 134 | ) 135 | message(toString(Sys.time()), " Streaming process started") 136 | } 137 | hometimeline <- connect2MongoDb("hometimeline") 138 | filterstream <- connect2MongoDb("filterstream") 139 | setwd(Sys.getenv("wd")) 140 | 141 | base_url <<- 142 | "https://stream.twitter.com/1.1/statuses/filter.json?" 143 | stop_filterstream <- FALSE 144 | #Write Status to file 145 | status <- file("stop_request.txt","w+b") 146 | writeLines("FALSE", status) 147 | close(status) 148 | fileid <<- 0 149 | while (stop_filterstream == FALSE) { 150 | kw_filename <- paste0("filterstream", fileid, ".json") 151 | if (type == 1) { 152 | testlist <- getTracklist(hometimeline, fileid) 153 | try(httr::GET( 154 | base_url, query = testlist,httr::config(token = makeOAuth(), timeout = timeout), 155 | httr::write_disk(kw_filename, overwrite = TRUE) 156 | ), silent = TRUE) 157 | } 158 | if (type == 2) { 159 | base_url <- Sys.getenv("query_url") 160 | message(paste(toString(Sys.time()), " STREAMLOOP Type 2: in progress")) 161 | try(httr::GET( 162 | base_url, httr::config(token = makeOAuth(), timeout = timeout), 163 | httr::write_disk(kw_filename, overwrite = TRUE) 164 | ), silent = TRUE) 165 | } 166 | command <- 167 | paste0("Rscript -e library(TwitteR2Mongo);import2mongo(",fileid,")") 168 | system(command = command, wait = FALSE) 169 | 170 | # Check if stop is requested 171 | status <- file("stop_request.txt","rb") 172 | stop_filterstream <- readLines(status, n = 1) 173 | close(status) 174 | fileid <- fileid + 1 175 | } 176 | message(toString(Sys.time()), " Streaming process will now terminate.") 177 | unlink("stop_request.txt") 178 | } 179 | 180 | 181 | # Create the tracklist 182 | # Will NOT be exported. Used by: StreamingLoop 183 | 184 | getTracklist <- function(connection, fileid) { 185 | updateHometimeline() 186 | merge <- 187 | mergeHashtagFrames( 188 | topHashtagsInInterval(connection, interval = getInterval(60 * 24), 10), 189 | topHashtagsInInterval(connection, interval = getInterval(), 10) 190 | ) 191 | merge <- na.omit(merge) 192 | tracklist <- list() 193 | message( 194 | toString(Sys.time()), " STREAM: Tracklist generated writing to file no.", fileid, ", searching for: ", toString(merge[,1]) 195 | ) 196 | for (i in 1:nrow(merge)) { 197 | tracklist <- addToList(toString(merge[i,1]),tracklist) 198 | } 199 | #Collapse list to string 200 | testlist <- list(track = paste(tracklist, collapse = "%2C")) 201 | return(testlist) 202 | } 203 | 204 | 205 | # Add values to list in utf8-url encoding 206 | # Will NOT be exported. Used by: StreamingLoop 207 | addToList <- function(value, list) { 208 | list <- c(list, URLencode(value, reserved = TRUE)) 209 | return (list) 210 | } 211 | 212 | 213 | # Helper function deletes logfiles in working directory 214 | # Will NOT be exported. Used by: startStreaming 215 | clearLogfiles <- function() { 216 | unlink("logfile_dates.txt") 217 | unlink("logfile_filterstream.txt") 218 | unlink("logfile_import.txt") 219 | } 220 | -------------------------------------------------------------------------------- /R/geoLocation.R: -------------------------------------------------------------------------------- 1 | #' Extract Coordinates 2 | #' 3 | #' Exports Point and Polygon coordinates from the geo fields of the tweet 4 | #' The function currently supports coordinates of the type point and bounding box. 5 | #' The coordinates can be shown on a map using \link{drawMap} 6 | #' 7 | #' @param connection The name of a MongoDB connection 8 | #' @param searchterm A term all tweets returned contain 9 | #' @param limit Maximum number of tweets to retrive from db 10 | #' 11 | #' @return dataframe with coordinates (lat,long) 12 | #' 13 | #' @examples 14 | #' #extractCoordinates(connection = "filterstream", searchterm = c("Trump")) 15 | #' 16 | #' @export 17 | extractCoordinates <- 18 | function(connection, searchterm, limit = 15000) { 19 | mconnection <- connect2MongoDb(connection) 20 | points <- 21 | mconnection$find(buildRegexQuery(searchterm), getMongoFields( 22 | c( 23 | "place.bounding_box.coordinates","geo","text", "user.location" 24 | ) 25 | ),limit = limit) 26 | 27 | for (i in 1:length(points$text)) { 28 | line <- NULL 29 | #Check if any points geo included 30 | if (!is.atomic(points$geo)) { 31 | line <- (unlist(points$geo$coordinates[i])) 32 | } 33 | 34 | if (is.null(line)) { 35 | ul <- unlist(points$place$bounding_box$coordinates[i]) 36 | line <- (ul[5] + ul[6] + ul[7] + ul[8]) / 4 37 | line <- append(line,(ul[1] + ul[2] + ul[3] + ul[4]) / 4) 38 | } 39 | points$lon[i] <- line[2] 40 | points$lat[i] <- line[1] 41 | } 42 | return(points) 43 | } 44 | 45 | #' Geocorde DataFrame 46 | #' 47 | #' Converts a information from the user.location field into lat/lon coordinates 48 | #' using the google maps API 49 | #' 50 | #' @param places a dataframe with at least one column containing the userLocation and google API 51 | #' @param replace bolean value to define if existing lon/lat values should be replaced 52 | #' 53 | #' @return dataframe with coordinates (lat,long) 54 | #' 55 | #' @examples 56 | #' #geocodeDataFrame(df) 57 | #' 58 | #' @import ggmap 59 | #' @import maps 60 | #' 61 | #' @export 62 | geocodeDataFrame <- function(places, replace = FALSE) { 63 | #Create columns if not existing 64 | if ((!"lon" %in% colnames(places)) && 65 | (!"lon" %in% colnames(places))) { 66 | places$lon <- NA 67 | places$lat <- NA 68 | } 69 | 70 | if (file.exists("locationscache.Rda")) { 71 | load("locationscache.Rda") 72 | } 73 | else { 74 | location <- ggmap::geocode("London", source = "google") 75 | locdb <- 76 | as.data.frame(matrix( 77 | c("London",location[1],location[2]),nrow = 1,ncol = 3 78 | )) 79 | colnames(locdb) <- c("place","lon","lat") 80 | } 81 | savecount <- 0 82 | 83 | for (i in 1:nrow(places)) { 84 | #Check if empty 85 | if (is.na(places$user$location[i]) | 86 | (places$user$location[i] == "")) { 87 | #do nothing 88 | } 89 | else { 90 | #Check if value is already set 91 | if (is.na(places$lon[i]) && replace == FALSE) { 92 | #Check if already in cache 93 | values <- 94 | locdb[locdb$place == places$user$location[i],c("lon","lat")] 95 | if (length(values$lon) == 1) { 96 | places$lon[i] <- unlist(values$lon) 97 | places$lat[i] <- unlist(values$lat) 98 | print("Cached DS") 99 | } 100 | else { 101 | location <- 102 | geocode(toString(places$user$location[i]), source = "google") 103 | places$lon[i] <- location[1] 104 | places$lat[i] <- location[2] 105 | locdb <- 106 | rbind(locdb,data.frame( 107 | place = toString(places$user$location[i]),lon = location[1],lat = location[2] 108 | 109 | )) 110 | if (savecount == 100) { 111 | save(locdb,file = "locationscache.Rda") 112 | print("Updated cache") 113 | savecount = 0 114 | } 115 | savecount = savecount+1 116 | } 117 | } 118 | } 119 | } 120 | save(locdb,file = "locationscache.Rda") 121 | return(places) 122 | } 123 | 124 | 125 | #' Draw a Density Map 126 | #' 127 | #' Draws a Density Map of the coordinates 128 | #' 129 | #' @param data dataframe containing lat/lon coordinates 130 | #' @param location Area to show on the map 131 | #' @param zoom Zoom factor for the map 132 | #' @param fill boolean value to adjust if a filling is used 133 | #' 134 | #' @return map 135 | #' 136 | #' @examples 137 | #' #drawMap(df, "Europe", 4) 138 | #' 139 | #' @import ggplot2 140 | #' @export 141 | 142 | drawMap <- function(data, location, zoom, fill = FALSE) { 143 | map <- get_map(location = location, zoom = zoom) 144 | if (fill) { 145 | ggmap(map, extent = "device") + geom_density2d(data = data, aes(x = lon, y = lat), size = 0.3) + 146 | stat_density_2d( 147 | data = data, aes( 148 | x = lon, y = lat, fill = ..level.., alpha = ..level.. 149 | ), size = 0.01, geom = "polygon" 150 | ) + 151 | scale_fill_gradient(low = "green", high = "red") + 152 | scale_alpha(range = c(0, 0.3), guide = FALSE) 153 | } 154 | 155 | else { 156 | ggmap(map, extent = "device") + geom_density2d(data = data, aes(x = lon, y = lat), size = 0.3) 157 | 158 | } 159 | } 160 | -------------------------------------------------------------------------------- /R/hometimeline.R: -------------------------------------------------------------------------------- 1 | #' Update Home Timeline 2 | #' 3 | #' Function to retrive and update the home timeline, the home timeline consist of up to 800 tweets 4 | #' posted by the accounts the user follows. Set Sys.setlocale("LC_TIME", "English") in order 5 | #' to be able to correctly process the twitter timestamp. See ?as.POSIXct for help. 6 | #' 7 | #' @param connection a mongoconnection to use (default: hometimeline) 8 | #' @param oAuth an oAuth token to use, by default a token is retrived by using \link{makeOAuth} 9 | #' 10 | #' @return None 11 | #' 12 | #' @examples 13 | #' #updateHometimeline() 14 | #' 15 | #' @export 16 | 17 | updateHometimeline <- 18 | function(connection = "hometimeline", oAuth = makeOAuth()) { 19 | tryCatch({ 20 | mconnection <- connect2MongoDb(connection) 21 | }, error = function(e) 22 | { 23 | stop( 24 | "Can not connect to MongoDB. The supplied connection does not work or the default Hometimeline does not exist. 25 | use setMongoDbCredentials()" 26 | ) 27 | }) 28 | connection = "hometimeline" 29 | mconnection <- connect2MongoDb(connection) 30 | oAuth = makeOAuth() 31 | fileid <- 0 32 | since_id <- 33 | mconnection$find('{}','{"id":1,"_id":0, "created_at":1}','{"id":-1}',limit = 34 | 1) 35 | if (length(since_id) == 0) { 36 | since <- 1 37 | } 38 | else { 39 | since <- since_id[1,2] 40 | } 41 | for (i in 1:5) { 42 | filename <- paste0("home", i, ".json") 43 | #filename <- getFilename("home",) 44 | if (i == 1) { 45 | requestURL <- 46 | paste0( 47 | "https://api.twitter.com/1.1/statuses/home_timeline.json?count=200&since_id=",since 48 | ) 49 | } 50 | else { 51 | requestURL <- 52 | paste0( 53 | "https://api.twitter.com/1.1/statuses/home_timeline.json?count=200&max_id=",max_id, "&since_id=",since 54 | ) 55 | } 56 | httr::GET( 57 | requestURL, httr::config(token = oAuth), httr::write_disk(filename, overwrite = TRUE) 58 | ) 59 | json_data <- jsonlite::fromJSON(filename) 60 | 61 | 62 | Sys.setlocale("LC_TIME", "English") 63 | if (is.data.frame(json_data)) { 64 | max_id <- (min(json_data$id) - 65) 65 | json_data$timestamp_ms <- 66 | as.character(as.numeric( 67 | as.POSIXct(json_data$created_at, format = "%a %b %d %H:%M:%S %z %Y") 68 | ) * 1000) 69 | mconnection$insert(json_data) 70 | } 71 | else { 72 | 73 | message("Timeline is up to date") 74 | unlink(filename) 75 | break 76 | } 77 | unlink(filename) 78 | } 79 | } 80 | -------------------------------------------------------------------------------- /R/mongoConnection.R: -------------------------------------------------------------------------------- 1 | #' Set MongoDB Credentials 2 | #' 3 | #' Function to set MongoDB credentials. Type can be hometimeline or filterstream. 4 | #' Creates either hometimeline or filterstream as a connection element. 5 | #' 6 | #' @param type Type to set the MongoDB credentials for: hometimeline or filterstream 7 | #' @param collection The collection to store the tweets in 8 | #' @param db The database to store the tweets in 9 | #' @param url The path to the MongoDB 10 | #' 11 | #' @return None 12 | #' 13 | #' @examples 14 | #' setMongoDbCredentials (type = "hometimeline", collection = "hometimeline", 15 | #' db = "twitter", url = "mongodb://localhost") 16 | #' 17 | #' @import mongolite 18 | #' @export 19 | 20 | setMongoDbCredentials <- function(type, collection, db, url) { 21 | if ((!class(type) == "character") || 22 | (!class(collection) == "character") || 23 | (!class(db) == "character") || (!class(url) == "character")) { 24 | stop("All parameters must be characters") 25 | } 26 | if (type == "hometimeline") { 27 | Sys.setenv( 28 | collection_home = "hometimeline", db_home = "twitter", 29 | url_home = "mongodb://localhost" 30 | ) 31 | } 32 | else if (type == "filterstream") { 33 | Sys.setenv( 34 | collection_filter = "filterstream", db_filter = "twitter", 35 | url_filter = "mongodb://localhost" 36 | ) 37 | } 38 | else { 39 | message("Type must be filterstream or hometimeline") 40 | } 41 | } 42 | 43 | #' Establish a connection to mongoDB 44 | #' 45 | #' Connect to MongoDB using the credentials stored with \code{\link{setMongoDbCredentials}} 46 | #' Creates either hometimeline or filterstream as a connection element. 47 | #' 48 | #' @param type Type to set the MongoDB credentials for: hometimeline or filterstream 49 | #' 50 | #' @return Connection Object 51 | #' 52 | #' @examples 53 | #' setMongoDbCredentials (type = "hometimeline", collection = "hometimeline", 54 | #' db = "twitter", url = "mongodb://localhost") 55 | #' 56 | #' @export 57 | #' 58 | connect2MongoDb <- function(type) { 59 | if (!class(type) == "character") { 60 | stop("Type parameter must be a character") 61 | } 62 | if (type == "hometimeline") { 63 | tryCatch({ 64 | return( 65 | mongo( 66 | collection = Sys.getenv("collection_home"), 67 | db = Sys.getenv("db_home"), 68 | url = Sys.getenv("url_home"), 69 | verbose = TRUE 70 | ) 71 | ) 72 | }, error = function(e) 73 | { 74 | stop( 75 | "Can not connect to MongoDB, wrong credentials or database not available. 76 | Please use setMongoDbCredentials." 77 | ) 78 | }) 79 | } 80 | else if (type == "filterstream") { 81 | tryCatch({ 82 | return( 83 | mongo( 84 | collection = Sys.getenv("collection_filter"), 85 | db = Sys.getenv("db_filter"), 86 | url = Sys.getenv("url_filter"), 87 | verbose = TRUE 88 | ) 89 | ) 90 | }, error = function(e) 91 | { 92 | stop( 93 | "Can not connect to MongoDB, wrong credentials or database not available. 94 | Please use setMongoDbCredentials." 95 | ) 96 | }) 97 | } 98 | else { 99 | stop("Type must be filterstream or hometimeline") 100 | } 101 | } 102 | -------------------------------------------------------------------------------- /R/mongoQueries.R: -------------------------------------------------------------------------------- 1 | #' createTwitterTimeline 2 | #' 3 | #' Creates a time series of hashtags found in the given time interval. 4 | #' Is being used by createTwitterTimeSeries(). Parameter interval may consist 5 | #' of an interval vector created by createIntervalVector(). See examples. 6 | #' 7 | #' @param mongo a mongoDB connection to use 8 | #' @param interval which will be used to aggregate the hashtags in the mongodb. 9 | #' 10 | #' @return dataframe containing all hashtags with count of the respective time interval 11 | #' 12 | #' @examples 13 | #' #createTwitterTimeline(hometimeline, 14 | #' # createIntervalVector(c("2015-12-15 00:00:01","2015-12-17 14:59:59"),3)) 15 | #' @import stringr 16 | #' @export 17 | createTwitterTimeline <- function(mongo, interval) { 18 | # basequery 19 | interval <- as.character(interval) 20 | basequery <- '[{"$match": {"timestamp_ms": {"$gt": "intervalstart", "$lte": "intervalend"}}}, 21 | {"$unwind": "$entities.hashtags"}, 22 | {"$project": {"entities.hashtags": {"$toLower": "$entities.hashtags.text"}}}, 23 | {"$group": {"_id":"$entities.hashtags","count":{"$sum":1}}}, 24 | {"$sort": {"count":-1}}]' 25 | 26 | # insert respective interval into basequery 27 | for (i in 1:(length(interval) - 1)) { 28 | query <- stringr::str_replace_all(stringr::str_c(basequery), 29 | c("intervalstart" = interval[i], 30 | "intervalend" = interval[i + 1])) 31 | 32 | if (i == 1) { 33 | # dataframe of the first interval, to which everything gets appended to 34 | toAppendTo <- mongo$aggregate(query) 35 | if ((length(toAppendTo) == 0) | (nrow(toAppendTo) < 2)) { 36 | stop( 37 | "First interval does not contain enough or any 38 | documents in the mongoDB. Decrease interval steps 39 | or increase interval length" 40 | ) 41 | } 42 | } 43 | else { 44 | # all further dataframes with more recent interval times. 45 | # they will be appended to the toAppendTo dataframe 46 | toAppendFrom <- mongo$aggregate(query) 47 | if (nrow(toAppendFrom) > 2) { 48 | toAppendTo <- appendDeltas(toAppendTo, toAppendFrom) 49 | } 50 | else { 51 | stop( 52 | paste0( 53 | "Not enough tweets in interval Nr.", i," . Increase 54 | decrease steps or increase interval size" 55 | ) 56 | ) 57 | } 58 | } 59 | } 60 | interval <- timestampToUserdate(as.numeric(interval)) 61 | names(toAppendTo)[2:length(toAppendTo)] <- 62 | paste0(interval[1:(length(interval) - 1)]," to ",interval[2:length(interval)]) 63 | return(toAppendTo) 64 | } 65 | 66 | #' createIntervalVector 67 | #' 68 | #' Creates a time interval vector. Interval parameters passed may be an unixtimestamp 69 | #' (either in seconds or miliseconds), an interval of the twitter created_at format 70 | #' or an interval of the form YYYY-MM-DD HH:MM:SS. 71 | #' 72 | #' @param interval which will be divided into equally sized subintervals. 73 | #' Interval must be of the form \%d.\%m.\%Y \%HH:\%MM:\%SS, for example: 11.09.2015 00:00:01 74 | #' @param intervalsteps specifiy the amount of subintervals 75 | #' 76 | #' @return interval vector of unixtimestamps in ms 77 | #' 78 | #' @examples 79 | #' #createIntervalVector(c("2015-12-15 00:00:01","2015-12-17 14:59:59"),3) 80 | #' @export 81 | createIntervalVector <- function(interval, intervalsteps) { 82 | if (is.numeric(interval) == TRUE) { 83 | fullinterval <- 84 | seq( 85 | from = interval[1],to = interval[2], by = diff(interval) / intervalsteps 86 | ) 87 | 88 | if (all(nchar(interval, type = "chars") == 10)) { 89 | fullinterval <- fullinterval * 1000 90 | 91 | } 92 | } 93 | 94 | else if (is.character(interval) == TRUE) { 95 | if (all(grepl(pattern = "\\d{4}-\\d{2}-\\d{2} \\d{2}:\\d{2}:\\d{2}" ,x = interval)) == 96 | TRUE) { 97 | interval <- as.numeric(as.POSIXct(interval, format = "%Y-%m-%d %T")) 98 | } 99 | 100 | else if (all( 101 | grepl(pattern = "^\\w{3} \\w{3} \\d{2} \\d{2}:\\d{2}:\\d{2} \\+\\d{4} \\d{4}", x = interval) 102 | ) == TRUE) { 103 | interval <- 104 | as.numeric(as.POSIXct(interval, format = "%a %b %d %H:%M:%S %z %Y")) 105 | } 106 | 107 | fullinterval <- 108 | seq( 109 | from = interval[1],to = interval[2], by = diff(as.numeric(interval)) / intervalsteps 110 | ) 111 | fullinterval <- fullinterval * 1000 112 | } 113 | 114 | return(fullinterval) 115 | } 116 | 117 | 118 | #' cleanTwitterTimeline 119 | #' 120 | #' Cleans the dataframe returned by createTwitterTimeline. Inserts 0 for NaN and 121 | #' removes hashtags which lie unter a certain threshold with their total amount 122 | #' over all considered intervals.Threshold may be userspecified, if not will 123 | #' default to an implemented threshold. See defaultThreshold(). 124 | #' 125 | #' @param data to clean created by createTwitterTimeline() 126 | #' @param threshold (optional) under which values will be removed from the dataframe 127 | #' 128 | #' @return dataframe 129 | #' 130 | #' @examples 131 | #' #cleanTwitterTimeline(data, threshold = NULL) 132 | #' #cleanTwitterTimeline(data, threshold = 10) 133 | #' @export 134 | cleanTwitterTimeline <- function(data, threshold = NULL) { 135 | 136 | data[is.na(data)] <- 0 137 | 138 | if (is.null(threshold)) { 139 | threshold <- defaultThreshold(data) 140 | } 141 | sums <- c() 142 | for (i in 1:nrow(data)) { 143 | sums <- c(sums, sum(data[i,2:length(data)])) 144 | } 145 | 146 | index <- which(sums < threshold) 147 | data <- data[-c(index) ,] 148 | names(data)[1] <- "Hashtag" 149 | rownames(data) <- 1:nrow(data) 150 | return(data) 151 | } 152 | 153 | 154 | 155 | #' defaultThreshold 156 | #' 157 | #' Calculates a threshlod value to remove hashtags from a dataframe 158 | #' which have in sum a smaller count than the defined threshold. 159 | #' Threshold is the next greatet number of the mean. Used by 160 | #' cleanTwitterTimeline(). 161 | #' 162 | #' @param data to calculate the threshold for. 163 | #' 164 | #' @return threshold integer 165 | #' 166 | #' @examples 167 | #' #defaultThreshold(data) 168 | #' @export 169 | defaultThreshold <- function(data) { 170 | # calculate default threshold for the dataframe. i.e the value, 171 | # at which hashtags with an accumulated count lower than the threshold 172 | # are discarded 173 | 174 | # replace NA's and NaN in data frame 175 | data[is.na(data)] <- 0 176 | # calculat accummulated values 177 | sums <- c() 178 | for (i in 1:nrow(data)) { 179 | sums <- c(sums, sum(data[i,2:length(data)])) 180 | } 181 | # return threshold round up the mean(sum) to the next bigger number 182 | return(ceiling(mean(sums))) 183 | } 184 | 185 | 186 | #' absoluteHashtagCount 187 | #' 188 | #' Sums up the time series dataframe to get absolute counts 189 | #' of a given time interval. 190 | #' 191 | #' @param dataframe to transform 192 | #' @param interval for the specified timeframe 193 | #' 194 | #' @return interval which has been used to run createTwitterTimeline() 195 | #' 196 | #' @examples 197 | #' #absoluteHashtagCount(dataframe, interval) 198 | #' @export 199 | absoluteHashtagCount <- function(dataframe, interval) { 200 | dataframe[is.na(dataframe)] <- 0 201 | 202 | for (i in 1:nrow(dataframe)) { 203 | for (j in 1:(length(dataframe) - 2)) 204 | dataframe[i,j + 2] <- sum(dataframe[i,(j + 1):(j + 2)]) 205 | } 206 | 207 | return(dataframe) 208 | } 209 | 210 | 211 | 212 | #' rankTweets 213 | #' 214 | #' Ranks the hashtags according to their respective counts. Highest 215 | #' count in a given interval is being assigned rank 1. Second highest 216 | #' counts rank 2 and so on. 217 | #' 218 | #' @param data dataframe time series to rank. 219 | #' 220 | #' @return dataframe consisting of ranked hashtags 221 | #' 222 | #' @examples 223 | #' #rankTweets(dataframe) 224 | #' @export 225 | rankTweets <- function(data) { 226 | for (column in 2:length(data)) { 227 | data <- data[order(data[column],decreasing = TRUE),] 228 | 229 | uniques <- unlist(unique(data[column])) 230 | 231 | rank <- 1 232 | for (row in 1:nrow(data)) { 233 | if (data[row,column] == uniques[rank]) { 234 | data[row,column] <- rank 235 | } 236 | else { 237 | rank <- rank + 1 238 | data[row,column] <- rank 239 | } 240 | } 241 | } 242 | return(data) 243 | } 244 | 245 | 246 | # Helperfunction 247 | appendDeltas <- function(toAppendTo, toAppendFrom) { 248 | 249 | indexmatch <- match(toAppendFrom[,1], toAppendTo[,1]) 250 | 251 | 252 | elementpositionToExtract <- which(!is.na(indexmatch)) 253 | 254 | 255 | toAppendTo[,paste0("new",(length(toAppendTo) - 1))] <- NaN 256 | 257 | 258 | for (i in 1:sum(!is.na(indexmatch))) { 259 | toAppendTo[indexmatch[elementpositionToExtract[i]],length(toAppendTo)] <- 260 | toAppendFrom[elementpositionToExtract[i],2] 261 | 262 | } 263 | 264 | columnsToAdd <- length(toAppendTo) - length(toAppendFrom) 265 | toAppendFrom[,c(paste0("new",seq(columnsToAdd)))] <- NaN 266 | names(toAppendFrom) <- names(toAppendTo) 267 | toAppendFrom[2:length(toAppendFrom)] <- 268 | toAppendFrom[(length(toAppendFrom):2)] 269 | toAppendTo <- 270 | rbind.data.frame(toAppendTo, toAppendFrom[which(is.na(indexmatch)),]) 271 | return(toAppendTo) 272 | } 273 | 274 | 275 | #' createTwitterTimeSeries 276 | #' 277 | #' Creates a time series of hashtags found in the given time interval. 278 | #' The time series gets cleaned by cleanTwitterTimeline() and ordered 279 | #' in decreasing fashion with respect to the last column. 280 | #' 281 | #' @param mongo mongo instance to use 282 | #' @param interval timeinterval 283 | #' @param intervalsteps number of parts to divide the interval into 284 | #' 285 | #' @return dataframe 286 | #' 287 | #' @examples 288 | #' #timeseries <- 289 | #' # createTwitterTimeSeries(hometimeline,c("2015-12-15 00:00:01","2015-12-17 14:59:59"),3) 290 | #' @export 291 | createTwitterTimeSeries <- function(mongo, interval, intervalsteps) { 292 | 293 | timeseries <- createTwitterTimeline(mongo, createIntervalVector(interval, intervalsteps)) 294 | timeseries <- cleanTwitterTimeline(timeseries) 295 | timeseries <- timeseries[order(timeseries[ncol(timeseries)],decreasing = TRUE),] 296 | return(timeseries) 297 | } 298 | 299 | #' plotTweets 300 | #' 301 | #' Plots a dataframe in order to visualize the sum of hashtags in a 302 | #' given time interval. 303 | #' 304 | #' @param data dataframe to plot created by createTwitterTimeSeries() 305 | #' @param tophashtags number of hashtags to plot. 306 | #' @param interval specified time interval. Relevant for the x-axis of the plot. 307 | #' 308 | #' @return plot of the given dataframe 309 | #' 310 | #' @examples 311 | #' #plots the top 10 hashtags 312 | #' #plotTweets(data,10) 313 | #' #interval <- createIntervalVector(c("2016-01-15 20:00:00", "2016-01-16 00:10:00"),9) 314 | #' #interval 315 | #' #plotTweets(data,10, interval) 316 | #' @export 317 | 318 | plotTweets <- function(data, tophashtags, interval) { 319 | values <- hashtag <- date <- NULL 320 | 321 | data <- head(data, tophashtags) 322 | rownames(data) <- data$Hashtag 323 | if(missing(interval)==TRUE) { 324 | dates <- colnames(data[,2:ncol(data)]) 325 | } 326 | else { 327 | dates <- as.POSIXct(interval[1:(length(interval)-1)]/1000, origin = "1970-01-01 00:00:00") 328 | } 329 | data <- as.data.frame(t(data[,2:ncol(data)])) 330 | data <- stack(data) 331 | data <- cbind.data.frame(data, rep(dates,tophashtags)) 332 | colnames(data) <- c("values","hashtag","date") 333 | pd <- position_dodge(0.001) 334 | ggplot(data, mapping = aes(x=date, y=values, color=hashtag, ymax = max(data[1]))) + geom_line(position=pd,aes(group=hashtag)) 335 | } 336 | 337 | 338 | -------------------------------------------------------------------------------- /R/regexBuilder.R: -------------------------------------------------------------------------------- 1 | #' buildRegexQuery 2 | #' 3 | #' Builds a regular expression query for mongoDB in json format, 4 | #' for the fields "entitites.hashtags.text" and "text". Can be use 5 | #' in conjunction with a time interval. 6 | #' 7 | #' @param regex the regular expression 8 | #' @param timestamp to retrieve hits only within a given interval 9 | #' @param fields to be searched by the regex. Default "text" and "entitites.hashtags.text". 10 | #' @param regexoption options used for the regex. Default is "i", case insensitivity. 11 | #' @param conjunction used to link the regex. Can only be "$and" or "$or". Default is "$or". 12 | #' 13 | #' @return query in jsonformat for mongolite 14 | #' 15 | #' @examples 16 | #' #buildRegexQuery(c("koln","koeln","berlin"), timestamp = getInterval( 17 | #' #inputinterval = c("2016-01-04 18:37:43 CET","2016-01-05 18:37:43 CET"))) 18 | #' 19 | #' #hometimeline$find(buildRegexQuery(c("koln","koeln"),timestamp = getInterval(60*24)), 20 | #' #getMongoFields(c("text","entitites.hashtags.text"))) 21 | #' @export 22 | 23 | buildRegexQuery <- function(regex, timestamp, fields = c("entitites.hashtags.text","text"), regexoption = "i", conjunction = "$or") { 24 | 25 | regexvector <- seq(1:(length(regex)*2)) 26 | replace_by_option <- which(regexvector%%2 == 0) 27 | replace_by_regex <- which(regexvector%%2 == 1) 28 | 29 | regexvector[replace_by_option] <- regexoption 30 | regexvector[replace_by_regex] <- regex 31 | 32 | regexquery <- operatorValuePair(c("$regex","$options"), regexvector) 33 | regexquery <- fieldValuePair(fields, regexquery, conjunction) 34 | 35 | if(!missing(timestamp)) { 36 | timestamp <- as.character(timestamp) 37 | timestampquery <- operatorValuePair(c("$gte","$lt"), timestamp) 38 | timestampquery <- fieldValuePair(c("timestamp_ms"), timestampquery) 39 | query <- useConjunction(timestampquery, regexquery, "$and") 40 | } 41 | 42 | else { 43 | query <- regexquery 44 | } 45 | return(query) 46 | } 47 | 48 | 49 | 50 | #' fieldValuePair 51 | #' 52 | #' Creates field value pair, called by buildRegexQuery 53 | #' 54 | #' @param key, fields to search. "text" or "entitites.hashtags.text" 55 | #' @param value, regex and options as value. use operatorValuePair() 56 | #' @param conjunction used for the regular expressions. Can only by "$and" or "$or" 57 | #' 58 | #' @return field value pair used by buildRegexQuery() 59 | #' 60 | #' @examples 61 | #' #fieldValuePair(key = c("entitites.hashtags.text","text"),value = 62 | #' #operatorValuePair(c("$regex","$options"),c("syrien","i")),"$or") 63 | #' 64 | #' @export 65 | 66 | fieldValuePair <- function(key, value, conjunction) { 67 | 68 | 69 | querystring <- NULL 70 | pastestring <- NULL 71 | 72 | if(length(key)==1) { 73 | for(i in 1:length(value)) { 74 | 75 | querystring[i] <- jsonlite::toJSON(setNames(as.list(value[i]), key)) 76 | } 77 | } 78 | 79 | else { 80 | for(i in 1:length(value)) { 81 | 82 | pastestring[i] <- jsonlite::toJSON(setNames(as.list(value[i]), key[2])) 83 | querystring[i] <- jsonlite::toJSON(setNames(as.list(value[i]), key[1])) 84 | } 85 | pastestring <- gsub(pattern = "(\\[\")|\\\\|(\"\\])",replacement = "", x = pastestring) 86 | } 87 | 88 | querystring <- gsub(pattern = "(\\[\")|\\\\|(\"\\])",replacement = "", x = querystring) 89 | 90 | if(length(key)>1) { 91 | querystring <- paste(querystring, pastestring , collapse = ",", sep = ",") 92 | 93 | } 94 | else { 95 | querystring <- paste(querystring, collapse = ",", sep = ",") 96 | } 97 | if(!missing(conjunction)) { 98 | querystring <- jsonlite::toJSON(setNames(as.list( querystring), conjunction)) 99 | querystring <- gsub(pattern = "\\\\", replacement = "", x = querystring) 100 | querystring <- gsub(pattern = "(\\:\\[\")(\\{.*\\})(\"\\])", replacement = ":[\\2]", x = querystring) 101 | } 102 | 103 | return(querystring) 104 | } 105 | 106 | #' operatorValuePair 107 | #' 108 | #' Creates operator value pair, called by buildRegexQuery. 109 | #' 110 | #' @param key of the key/value pair. Is always a mongo operator like $regex 111 | #' @param value of the key/value pair. Can be the regex and/or the corresponding option. 112 | #' 113 | #' @return operator value pair 114 | #' 115 | #' @examples 116 | #' #operatorValuePair(c("$regex","$options"),c("koln","i")) 117 | #' 118 | #' @export 119 | 120 | operatorValuePair <- function(key,value) { 121 | 122 | querystring <- NULL 123 | if ((length(value)==1)&&(length(key)==1)) { 124 | 125 | querystring <- jsonlite::toJSON(setNames(as.list(value), key)) 126 | } 127 | else if (((length(key)==1)&&(length(value)>1))) { 128 | 129 | for(i in 1:(length(value)/length(key))) { 130 | querystring[i] <- jsonlite::toJSON(setNames(as.list(value[i]), key)) 131 | } 132 | } 133 | else { 134 | for(i in 1:(length(value)/length(key))) { 135 | 136 | querystring[i] <- jsonlite::toJSON(setNames(as.list(value[(i*2-1):(i*2)]), key)) 137 | } 138 | } 139 | querystring <- gsub(pattern = "\\[|\\]", replacement = "", x = querystring) 140 | return(querystring) 141 | } 142 | 143 | #' useConjunction 144 | #' 145 | #' Connects query parts with either $and or $or. 146 | #' 147 | #' @param firstpart first part of the query 148 | #' @param secondpart second part of the query 149 | #' @param conjunction which can only be "$and" or "$or" 150 | #' 151 | #' @return linked mongo query parts. 152 | #' 153 | #' @examples 154 | #' useConjunction(c("$regex","$options"),c("syrien","i"),"$and") 155 | #' @export 156 | 157 | useConjunction <- function(firstpart, secondpart, conjunction) { 158 | querystring <- paste(firstpart, secondpart, sep =",") 159 | querystring <- jsonlite::toJSON(setNames(as.list(querystring), conjunction)) 160 | querystring <- gsub(pattern = "\\\\", replacement = "", x = querystring) 161 | querystring <- gsub(pattern = "(\\:\\[\")(\\{.*\\})(\"\\])", replacement = ":[\\2]", x = querystring) 162 | 163 | return(querystring) 164 | } 165 | 166 | #' getMongoFields 167 | #' 168 | #' Creates JSON formated string of fields to be returned by a mongo find query, 169 | #' so one does not have to write a JSON string "by hand". 170 | #' 171 | #' @param fields character vector of fields to be returned by a mongoDB query 172 | #' 173 | #' @return JSON format list of field to be returned 174 | #' 175 | #' @examples 176 | #' #getMongoFields(c("text","created_at")) 177 | #' 178 | #' #getInterval(60*24)), getMongoFields(c("text","entitites.hashtags.text","created_at"))) 179 | #' @export 180 | 181 | getMongoFields <- function(fields) { 182 | fields[length(fields) + 1] <- "_id" 183 | 184 | values <- c(rep(1,length(fields) - 1),0) 185 | 186 | jsonstring <- jsonlite::toJSON(setNames(as.list(values), fields)) 187 | 188 | jsonstring <- 189 | gsub(pattern = "\\[|\\]",replacement = "",x = jsonstring) 190 | 191 | return(jsonstring) 192 | } 193 | 194 | 195 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # TwitteR2Mongo 2 | R Package to stream and analyze tweets using a mongodb 3 | -------------------------------------------------------------------------------- /inst/doc/TwitteR2Mongo.R: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /inst/doc/TwitteR2Mongo.Rmd: -------------------------------------------------------------------------------- 1 | --- 2 | title: "TwitteR2Mongo" 3 | author: "Philipp Prettl and Lion Weber" 4 | date: "`r Sys.Date()`" 5 | output: rmarkdown::html_vignette 6 | vignette: > 7 | %\VignetteIndexEntry{TwitteR2Mongo} 8 | %\VignetteEngine{knitr::rmarkdown} 9 | %\VignetteEncoding{UTF-8} 10 | --- 11 | 12 | ## Introduction 13 | 14 | We are happy to introduce our new package TwitteR2Mongo connecting the Twitter API to the MongoDB using R. To ease storing and processing of large ammonuts of tweets we use the MongoDB to store the tweets in different collections. Using this package it is possible to find the most common hashtags based on your personal network i.e. the people you follow on twitter. These hashtags can be used to track the topics and trends relevant in your personal network. 15 | 16 | The package accesses two different types of API 17 | 18 | - The REST API to pull the hometimeline of the user 19 | - The Streaming API to filter all tweets posted on twitter on relevant keywords 20 | 21 | The relevant keywords for the Streaming API are gererated using the information from the hometimeline so all tweets with content relevant to the network observed are stored. These keywords are updated dynamically when new tweets appear on the hometimeline. Alternatively you can specify a query for the Twitter Streaming API and stream those. 22 | 23 | 24 | ## Getting Started 25 | 26 | To use this package a working mongoDB installation is required. You can start the MongoDB server by running: 27 | 28 | ``` 29 | mongod 30 | ``` 31 | 32 | If it is the first time you start the MongoDB server you need to create a writeable directory `C:/data/db` (Windows). For a local MongoDB installation the following information should be sufficient. 33 | 34 | ```r 35 | # Load the package 36 | library(TwitteR2Mongo) 37 | # Specify the two collections to use for storing the tweets 38 | setMongoDbCredentials(type = "hometimeline", collection = "hometimeline", db = "twitter", 39 | url = "mongodb://localhost") 40 | setMongoDbCredentials(type = "filterstream", collection = "filterstream", db = "twitter", 41 | url = "mongodb://localhost") 42 | 43 | # Check the connection 44 | hometimeline <- connect2MongoDb("hometimeline") 45 | filterstream <- connect2MongoDb("filterstream") 46 | 47 | ``` 48 | 49 | Additionally you need a Twitter Account. Using this account you can register a Twitter App at: [Twitter Application Management](https://apps.twitter.com/) and get your Consumer Key (API Key) and Consumer Secret (API Secret). Make sure to set the Callback URL to: `http://127.0.0.1:1410`. 50 | 51 | To connect to the Twitter-API first set your credentials using: 52 | 53 | ```r 54 | setAPICredentials(key = "your-API-KEY", secret = "your-API-SECRET") 55 | makeOAuth() 56 | ``` 57 | 58 | Please use the option to store the oAuth in a file(`.httr-oauth`) as the Streaming will not work without it. 59 | 60 | ## The Hometimeline 61 | 62 | The hometimeline contains up to 800 tweets posted by users you follow. Depending on how many users you 63 | are currently following, you should think about updating your hometimelime regularly. 64 | 65 | ```r 66 | # Create a connection to the collection holding the hometimeline 67 | hometimeline <- connect2MongoDb("hometimeline") 68 | 69 | # Retrive the most recent tweets via updateHometimeline() 70 | updateHometimeline() 71 | 72 | ``` 73 | 74 | 75 | getInterval() returns a unixtimestamp interval. Use Sys.setlocale("LC_TIME","English"), because Twitter provides a timestamp (later the "created _at" field) which needs an English environment to be properly parsed. For details see ?as.POSIXct. If no parameters have been passed on, the function returns an interval corresponding to the last hour. If you want to have an interval which is equivalent to the last 24 hours use getInterval(60*24) (i.e. 60minutes * 24 hours). Additionally you can pass on a vector of date times via inputinterval as shown in the example below. Refrain from using the times 00:00:00 and 12:00:00. They won't be parsed. Use 00:00:01 etc. instead. When working with the twitter API you should keep in mind, that the dates provided are always in GMT. 76 | 77 | ```r 78 | #Set digits to 13 in order see the exact unixtimestamp in ms 79 | options( digits = 13) 80 | 81 | #interval of the last hour 82 | getInterval() 83 | 84 | #interval of the last 24 hours 85 | getInterval(60*24) 86 | 87 | #specified interval 88 | timeframe <- c("2016-01-04 18:37:43 CET","2016-01-05 18:37:43 CET") 89 | getInterval(inputinterval = timeframe) 90 | 91 | ``` 92 | 93 | 94 | Use topHashtagsInInterval() to extract the Top hashtags from your database. 95 | Get the Top 10 hastags in your network within the last 24 hours. 96 | If you want to access the tweets provided by the Streaming API, just 97 | substitute "hometimeline" by "filterstream" in order to access the other collection. 98 | 99 | ```r 100 | topHashtagsInInterval(hometimeline, interval = getInterval(60*24), 10) 101 | 102 | topHashtagsInInterval(hometimeline, interval = getInterval(inputinterval = timeframe), 10) 103 | 104 | ``` 105 | 106 | 107 | 108 | ## The Streaming Process 109 | 110 | The Top hastags are used to filter all tweets on twitter for relevant hashtags. To get these tweets we need to connect to the streaming API. Once started the package will continue to download and import tweets until it is stopped. The streaming process will be started in an additional R process, which handels the streaming process on its own and allows you to keep on working in your current one. The timeout indicates after how many seconds the process is restarted with updated filter parameters. Don't use too low values, otherwise you might be blacklisted by Twitter. You may also stream tweets independent from your hometimeline. You can specify various search queries as shown below. The streaming process can only be stopped by `stopStreaming()`. If a timeout occurs, then the process is not restared with new filter parameters but terminated. The higher the timeout is the longer the maximum waiting time for the process to terminate. 111 | WARNING: The stream may create tens of GB per day and consume a lot of working memory. Execept for testing it is recommended to run it on a seperate computer. Additionally it should have an SSD and you should think about indexing your data. For further information on indexes and why they might be helpful visit: https://docs.mongodb.org/manual/indexes/ . 112 | 113 | ```r 114 | # Start the streaming process 115 | startStreaming(timeout = 300) 116 | 117 | #Start the streaming process with a specified query_url 118 | startStreaming(60,"https://stream.twitter.com/1.1/statuses/filter.json?track=Trump") 119 | 120 | #Get a random sample of all tweets 121 | startStreaming(60,"https://stream.twitter.com/1.1/statuses/sample.json") 122 | 123 | # Stop the streaming process 124 | stopStreaming() 125 | ``` 126 | 127 | 128 | ## Illustrate the most important topics in your hometimeline 129 | 130 | 131 | Extract all hashtags from your mongoDB which have been posted in the time interval specified in createIntervalVector. CreateIntervalVector takes two date time strings in the following format "2016-01-14 23:00:01" or "2016-01-15 08:00:01". You may also use the TwitterAPI format, for example "Thu Jan 15 13:38:00 +0000 2016". It then calculates a time interval specified by the second parameter in the function and returns the corresponding unix timestamps. The example below creates an interval from the 14th of January 23:00:00 to the 15th of January 08:00:00, in hourly steps. 132 | 133 | ```r 134 | createIntervalVector(c("2016-01-14 23:00:01", "2016-01-15 08:00:01"),9) 135 | 136 | # Which corresponds to: 137 | "2016-01-14 23:00:01 CET" "2016-01-15 00:00:01 CET" 138 | "2016-01-15 01:00:01 CET" "2016-01-15 02:00:01 CET" 139 | "2016-01-15 03:00:01 CET" "2016-01-15 04:00:01 CET" 140 | "2016-01-15 05:00:01 CET" "2016-01-15 06:00:01 CET" 141 | "2016-01-15 07:00:01 CET" "2016-01-15 08:00:01 CET" 142 | 143 | ``` 144 | 145 | CreateTwitterTimeseries then queries the mongoDB and extracts all hashtags from the respective time intervals and constructs a data frame. ( Again a warning, if the amount of data is very large, this may take some time.) Additionally rare tweets whose sum during the time interval are below a certain threshold are being removed from the data frame. Afterwards the data frame is being ordered in decreasing fashion with respect to the last column. Then using plotTweets() plots the top x hashtags with respect to the last time interval. The function creates a timeseries via stacking the data frame and converting it into a vectorized representation, and then uses ggplot2 to plot. 146 | 147 | 148 | ```r 149 | timeseries <- createTwitterTimeSeries(filterstream, c("2016-01-14 23:00:01", "2016-01-15 08:00:01"),10) 150 | interval <- createIntervalVector(c("2016-01-14 23:00:01", "2016-01-15 08:00:01"),10) 151 | print(plotTweets(timeseries[2:nrow(timeseries),], 20, interval)) 152 | 153 | ``` 154 | 155 | ![alt text](figure/Timeline.png) 156 | 157 | rankTweets 158 | 159 | If you want to get a ranked representation of your data frame you can use 160 | rankTweets. This presentation ranks your tweets in the respective intervals, which may help to identify if a hashtag has become trending. 161 | 162 | ```r 163 | rankmoving <- rankTweets(timeseries) 164 | head(rankmoving, n = 10) 165 | ``` 166 | 167 | 168 | absoluteHashtagCounts 169 | 170 | If you want to sum up the counts of the respective intervals use absoluteHashtagCounts(). 171 | 172 | ```r 173 | counts <- absoluteHashtagCount(timeseries) 174 | 175 | ``` 176 | 177 | ## BuildRegexQuery 178 | 179 | 180 | The buildRegexQuery function builds a JSON string which allows you to search the mongo fields „entities.hashtags.text“ and „text“ for certain hashtags or words, in a given timeframe you might be interested in. Parameters you can pass on are the regular expression, a timestamp which defines your time interval (you can use getInterval() for that), the fields to be searched, the regex options supported by mongoDB and a conjunction. 181 | 182 | The example below builds a JSON string which looks for the hashtag #Trump in the timeframe 2016-01-15 03:00:01 to 2016-01-15 04:00:01, in the fields “entitites.hashtags.text” and “text”. The conjunction $or ensures that only one of the used regular expressions needs to be found in a tweet in order for the tweet to be returned (In this case we are only looking for one, but you can extend that to many regular expressions). Using the conjunction $and results in returned tweets which have all regular expressions in common. A couple of parameters have a standard input, see ?buildRegexQuery() for more details. 183 | 184 | ```r 185 | interval <- getInterval( inputinterval = c("2016-01-15 03:00:01", "2016-01-15 04:00:01")) 186 | query <- buildRegexQuery(c("Trump"), timestamp = interval) 187 | 188 | ``` 189 | 190 | Now using filterstream$find(query, fields), returns a data frame with tweets containing one of the regular expression hits and the three mongo fields “text”, “entitites.hashtags.text” and “created_at” specified by getMongoFields(). Note: Refrain from using regular expressions with the characters \, [ and ] since these characters are being replaced during the JSON string building process, thus falsifying your regex. Alternatively you can use a dummy like "regextobereplaced" and replace that dummy with a complicated regex after you have used buildRegexQuery(). 191 | 192 | ```r 193 | fields <- getMongoFields(c("text","entitites.hashtags.text","created_at")) 194 | 195 | data <- filterstream$find(query, fields) 196 | ``` 197 | 198 | 199 | ## Tweets on a density map 200 | 201 | You can add the coordinates of the tweets to a density map. This function will only extract the 202 | exact coordinates stored in the geo information of the tweet. 203 | 204 | ```r 205 | data <- extractCoordinates("filterstream", "Trump", 1600) 206 | ``` 207 | One can augment the number of geotagged tweets by using the user-location field. This textfiled is 208 | converted to lon/lat coordinates using the Google API. 209 | 210 | To avoid a cluster of tweets in the "center" of the country one should remove the tweets only containing the name of the country 211 | 212 | ```r 213 | data <- data[data$user$location != "USA", ] 214 | data <- data[data$user$location != "United States", ] 215 | data <- data[data$user$location != "United States of America", ] 216 | 217 | result <- geocodeDataFrame(data) 218 | 219 | drawMap(data = result, location = "USA", zoom = 4, fill = TRUE) 220 | 221 | ``` 222 | 223 | ![alt text](figure/Density.png) 224 | 225 | ## Logfiles 226 | 227 | The Streaming process creates two logfiles, as the seperate R instances can not print information to the console. They might be helpful in case something goes wrong with the streaming and updating process. 228 | The logfiles will be stored in your working directory. 229 | -------------------------------------------------------------------------------- /man/absoluteHashtagCount.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/mongoQueries.R 3 | \name{absoluteHashtagCount} 4 | \alias{absoluteHashtagCount} 5 | \title{absoluteHashtagCount} 6 | \usage{ 7 | absoluteHashtagCount(dataframe, interval) 8 | } 9 | \arguments{ 10 | \item{dataframe}{to transform} 11 | 12 | \item{interval}{for the specified timeframe} 13 | } 14 | \value{ 15 | interval which has been used to run createTwitterTimeline() 16 | } 17 | \description{ 18 | Sums up the time series dataframe to get absolute counts 19 | of a given time interval. 20 | } 21 | \examples{ 22 | #absoluteHashtagCount(dataframe, interval) 23 | } 24 | 25 | -------------------------------------------------------------------------------- /man/buildRegexQuery.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/regexBuilder.R 3 | \name{buildRegexQuery} 4 | \alias{buildRegexQuery} 5 | \title{buildRegexQuery} 6 | \usage{ 7 | buildRegexQuery(regex, timestamp, fields = c("entitites.hashtags.text", 8 | "text"), regexoption = "i", conjunction = "$or") 9 | } 10 | \arguments{ 11 | \item{regex}{the regular expression} 12 | 13 | \item{timestamp}{to retrieve hits only within a given interval} 14 | 15 | \item{fields}{to be searched by the regex. Default "text" and "entitites.hashtags.text".} 16 | 17 | \item{regexoption}{options used for the regex. Default is "i", case insensitivity.} 18 | 19 | \item{conjunction}{used to link the regex. Can only be "$and" or "$or". Default is "$or".} 20 | } 21 | \value{ 22 | query in jsonformat for mongolite 23 | } 24 | \description{ 25 | Builds a regular expression query for mongoDB in json format, 26 | for the fields "entitites.hashtags.text" and "text". Can be use 27 | in conjunction with a time interval. 28 | } 29 | \examples{ 30 | #buildRegexQuery(c("koln","koeln","berlin"), timestamp = getInterval( 31 | #inputinterval = c("2016-01-04 18:37:43 CET","2016-01-05 18:37:43 CET"))) 32 | 33 | #hometimeline$find(buildRegexQuery(c("koln","koeln"),timestamp = getInterval(60*24)), 34 | #getMongoFields(c("text","entitites.hashtags.text"))) 35 | } 36 | 37 | -------------------------------------------------------------------------------- /man/cleanTwitterTimeline.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/mongoQueries.R 3 | \name{cleanTwitterTimeline} 4 | \alias{cleanTwitterTimeline} 5 | \title{cleanTwitterTimeline} 6 | \usage{ 7 | cleanTwitterTimeline(data, threshold = NULL) 8 | } 9 | \arguments{ 10 | \item{data}{to clean created by createTwitterTimeline()} 11 | 12 | \item{threshold}{(optional) under which values will be removed from the dataframe} 13 | } 14 | \value{ 15 | dataframe 16 | } 17 | \description{ 18 | Cleans the dataframe returned by createTwitterTimeline. Inserts 0 for NaN and 19 | removes hashtags which lie unter a certain threshold with their total amount 20 | over all considered intervals.Threshold may be userspecified, if not will 21 | default to an implemented threshold. See defaultThreshold(). 22 | } 23 | \examples{ 24 | #cleanTwitterTimeline(data, threshold = NULL) 25 | #cleanTwitterTimeline(data, threshold = 10) 26 | } 27 | 28 | -------------------------------------------------------------------------------- /man/connect2MongoDb.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/mongoConnection.R 3 | \name{connect2MongoDb} 4 | \alias{connect2MongoDb} 5 | \title{Establish a connection to mongoDB} 6 | \usage{ 7 | connect2MongoDb(type) 8 | } 9 | \arguments{ 10 | \item{type}{Type to set the MongoDB credentials for: hometimeline or filterstream} 11 | } 12 | \value{ 13 | Connection Object 14 | } 15 | \description{ 16 | Connect to MongoDB using the credentials stored with \code{\link{setMongoDbCredentials}} 17 | Creates either hometimeline or filterstream as a connection element. 18 | } 19 | \examples{ 20 | setMongoDbCredentials (type = "hometimeline", collection = "hometimeline", 21 | db = "twitter", url = "mongodb://localhost") 22 | 23 | } 24 | 25 | -------------------------------------------------------------------------------- /man/createIntervalVector.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/mongoQueries.R 3 | \name{createIntervalVector} 4 | \alias{createIntervalVector} 5 | \title{createIntervalVector} 6 | \usage{ 7 | createIntervalVector(interval, intervalsteps) 8 | } 9 | \arguments{ 10 | \item{interval}{which will be divided into equally sized subintervals. 11 | Interval must be of the form \%d.\%m.\%Y \%HH:\%MM:\%SS, for example: 11.09.2015 00:00:01} 12 | 13 | \item{intervalsteps}{specifiy the amount of subintervals} 14 | } 15 | \value{ 16 | interval vector of unixtimestamps in ms 17 | } 18 | \description{ 19 | Creates a time interval vector. Interval parameters passed may be an unixtimestamp 20 | (either in seconds or miliseconds), an interval of the twitter created_at format 21 | or an interval of the form YYYY-MM-DD HH:MM:SS. 22 | } 23 | \examples{ 24 | #createIntervalVector(c("2015-12-15 00:00:01","2015-12-17 14:59:59"),3) 25 | } 26 | 27 | -------------------------------------------------------------------------------- /man/createTwitterTimeSeries.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/mongoQueries.R 3 | \name{createTwitterTimeSeries} 4 | \alias{createTwitterTimeSeries} 5 | \title{createTwitterTimeSeries} 6 | \usage{ 7 | createTwitterTimeSeries(mongo, interval, intervalsteps) 8 | } 9 | \arguments{ 10 | \item{mongo}{mongo instance to use} 11 | 12 | \item{interval}{timeinterval} 13 | 14 | \item{intervalsteps}{number of parts to divide the interval into} 15 | } 16 | \value{ 17 | dataframe 18 | } 19 | \description{ 20 | Creates a time series of hashtags found in the given time interval. 21 | The time series gets cleaned by cleanTwitterTimeline() and ordered 22 | in decreasing fashion with respect to the last column. 23 | } 24 | \examples{ 25 | #timeseries <- 26 | # createTwitterTimeSeries(hometimeline,c("2015-12-15 00:00:01","2015-12-17 14:59:59"),3) 27 | } 28 | 29 | -------------------------------------------------------------------------------- /man/createTwitterTimeline.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/mongoQueries.R 3 | \name{createTwitterTimeline} 4 | \alias{createTwitterTimeline} 5 | \title{createTwitterTimeline} 6 | \usage{ 7 | createTwitterTimeline(mongo, interval) 8 | } 9 | \arguments{ 10 | \item{mongo}{a mongoDB connection to use} 11 | 12 | \item{interval}{which will be used to aggregate the hashtags in the mongodb.} 13 | } 14 | \value{ 15 | dataframe containing all hashtags with count of the respective time interval 16 | } 17 | \description{ 18 | Creates a time series of hashtags found in the given time interval. 19 | Is being used by createTwitterTimeSeries(). Parameter interval may consist 20 | of an interval vector created by createIntervalVector(). See examples. 21 | } 22 | \examples{ 23 | #createTwitterTimeline(hometimeline, 24 | # createIntervalVector(c("2015-12-15 00:00:01","2015-12-17 14:59:59"),3)) 25 | } 26 | 27 | -------------------------------------------------------------------------------- /man/defaultThreshold.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/mongoQueries.R 3 | \name{defaultThreshold} 4 | \alias{defaultThreshold} 5 | \title{defaultThreshold} 6 | \usage{ 7 | defaultThreshold(data) 8 | } 9 | \arguments{ 10 | \item{data}{to calculate the threshold for.} 11 | } 12 | \value{ 13 | threshold integer 14 | } 15 | \description{ 16 | Calculates a threshlod value to remove hashtags from a dataframe 17 | which have in sum a smaller count than the defined threshold. 18 | Threshold is the next greatet number of the mean. Used by 19 | cleanTwitterTimeline(). 20 | } 21 | \examples{ 22 | #defaultThreshold(data) 23 | } 24 | 25 | -------------------------------------------------------------------------------- /man/drawMap.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/geoLocation.R 3 | \name{drawMap} 4 | \alias{drawMap} 5 | \title{Draw a Density Map} 6 | \usage{ 7 | drawMap(data, location, zoom, fill = FALSE) 8 | } 9 | \arguments{ 10 | \item{data}{dataframe containing lat/lon coordinates} 11 | 12 | \item{location}{Area to show on the map} 13 | 14 | \item{zoom}{Zoom factor for the map} 15 | 16 | \item{fill}{boolean value to adjust if a filling is used} 17 | } 18 | \value{ 19 | map 20 | } 21 | \description{ 22 | Draws a Density Map of the coordinates 23 | } 24 | \examples{ 25 | #drawMap(df, "Europe", 4) 26 | 27 | } 28 | 29 | -------------------------------------------------------------------------------- /man/extractCoordinates.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/geoLocation.R 3 | \name{extractCoordinates} 4 | \alias{extractCoordinates} 5 | \title{Extract Coordinates} 6 | \usage{ 7 | extractCoordinates(connection, searchterm, limit = 15000) 8 | } 9 | \arguments{ 10 | \item{connection}{The name of a MongoDB connection} 11 | 12 | \item{searchterm}{A term all tweets returned contain} 13 | 14 | \item{limit}{Maximum number of tweets to retrive from db} 15 | } 16 | \value{ 17 | dataframe with coordinates (lat,long) 18 | } 19 | \description{ 20 | Exports Point and Polygon coordinates from the geo fields of the tweet 21 | The function currently supports coordinates of the type point and bounding box. 22 | The coordinates can be shown on a map using \link{drawMap} 23 | } 24 | \examples{ 25 | #extractCoordinates(connection = "filterstream", searchterm = c("Trump")) 26 | 27 | } 28 | 29 | -------------------------------------------------------------------------------- /man/fieldValuePair.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/regexBuilder.R 3 | \name{fieldValuePair} 4 | \alias{fieldValuePair} 5 | \title{fieldValuePair} 6 | \usage{ 7 | fieldValuePair(key, value, conjunction) 8 | } 9 | \arguments{ 10 | \item{key, }{fields to search. "text" or "entitites.hashtags.text"} 11 | 12 | \item{value, }{regex and options as value. use operatorValuePair()} 13 | 14 | \item{conjunction}{used for the regular expressions. Can only by "$and" or "$or"} 15 | } 16 | \value{ 17 | field value pair used by buildRegexQuery() 18 | } 19 | \description{ 20 | Creates field value pair, called by buildRegexQuery 21 | } 22 | \examples{ 23 | #fieldValuePair(key = c("entitites.hashtags.text","text"),value = 24 | #operatorValuePair(c("$regex","$options"),c("syrien","i")),"$or") 25 | 26 | } 27 | 28 | -------------------------------------------------------------------------------- /man/geocodeDataFrame.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/geoLocation.R 3 | \name{geocodeDataFrame} 4 | \alias{geocodeDataFrame} 5 | \title{Geocorde DataFrame} 6 | \usage{ 7 | geocodeDataFrame(places, replace = FALSE) 8 | } 9 | \arguments{ 10 | \item{places}{a dataframe with at least one column containing the userLocation and google API} 11 | 12 | \item{replace}{bolean value to define if existing lon/lat values should be replaced} 13 | } 14 | \value{ 15 | dataframe with coordinates (lat,long) 16 | } 17 | \description{ 18 | Converts a information from the user.location field into lat/lon coordinates 19 | using the google maps API 20 | } 21 | \examples{ 22 | #geocodeDataFrame(df) 23 | 24 | } 25 | 26 | -------------------------------------------------------------------------------- /man/getInterval.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/dateOperation.R 3 | \name{getInterval} 4 | \alias{getInterval} 5 | \title{Get Interval} 6 | \usage{ 7 | getInterval(decrease = 60, adjust = 0, inputinterval) 8 | } 9 | \arguments{ 10 | \item{decrease}{size of interval (in minutes)} 11 | 12 | \item{adjust}{time to subtract from system time to get GMT (in minutes)} 13 | 14 | \item{inputinterval}{alternatively input a time interval} 15 | } 16 | \value{ 17 | interval 18 | } 19 | \description{ 20 | Calculates an intervall from now-decrease until now. Twitter uses GMT therefore 21 | the supplied time can be modifed by adjust, default is for German daylight saving time. 22 | Alternatively an interval may be provided and the corresponding unix timestamps will 23 | be returned. Set Sys.setlocale("LC_TIME", "English") in order 24 | to be able to correctly process the twitter timestamp. Avoid timestamps with the 25 | times 00:00:00 and 12:00:00 since they are a digit short. 26 | } 27 | \examples{ 28 | #Get an interval covering the last 24 hours 29 | getInterval(60*24) 30 | 31 | #Get an interval covering the last hour 32 | getInterval() 33 | 34 | #Specify interval and get corresponding unix timestamps 35 | #isodate <- c("2016-01-04 18:37:43","2016-01-05 18:37:43") 36 | #getInterval(inputinterval = isodate) 37 | 38 | #twitter <- c("Tue Jan 05 12:51:00 +0000 2016","Tue Jan 05 16:51:00 +0000 2016") 39 | #twitter <- getInterval(inputinterval = twitter) 40 | 41 | } 42 | 43 | -------------------------------------------------------------------------------- /man/getMongoFields.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/regexBuilder.R 3 | \name{getMongoFields} 4 | \alias{getMongoFields} 5 | \title{getMongoFields} 6 | \usage{ 7 | getMongoFields(fields) 8 | } 9 | \arguments{ 10 | \item{fields}{character vector of fields to be returned by a mongoDB query} 11 | } 12 | \value{ 13 | JSON format list of field to be returned 14 | } 15 | \description{ 16 | Creates JSON formated string of fields to be returned by a mongo find query, 17 | so one does not have to write a JSON string "by hand". 18 | } 19 | \examples{ 20 | #getMongoFields(c("text","created_at")) 21 | 22 | #getInterval(60*24)), getMongoFields(c("text","entitites.hashtags.text","created_at"))) 23 | } 24 | 25 | -------------------------------------------------------------------------------- /man/import2mongo.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/filterstream.R 3 | \name{import2mongo} 4 | \alias{import2mongo} 5 | \title{Importing a filterstream file to mongoDB.} 6 | \usage{ 7 | import2mongo(fileid, connection = "filterstream", createLog = TRUE) 8 | } 9 | \arguments{ 10 | \item{fileid}{Nnumber of the file to import} 11 | 12 | \item{connection}{A mongo db connection} 13 | 14 | \item{createLog}{If set to FALSE output is send to the 15 | console instead of the logfile (logfile_import.txt)} 16 | } 17 | \value{ 18 | none 19 | } 20 | \description{ 21 | Used to import fiterstream files to mongo 22 | in a seperate R process. Can be used to import tweets 23 | manually for times of MongoDB downtime. The file to import 24 | must be located in the directory set in sys.setenv("wd" =) 25 | } 26 | \examples{ 27 | #import2mongo(2) 28 | 29 | } 30 | 31 | -------------------------------------------------------------------------------- /man/makeOAuth.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/authentification.R 3 | \name{makeOAuth} 4 | \alias{makeOAuth} 5 | \title{Make OAuth} 6 | \usage{ 7 | makeOAuth(key = Sys.getenv("twitter_key"), 8 | secret = Sys.getenv("twitter_secret")) 9 | } 10 | \arguments{ 11 | \item{key}{The key for the Twitter-API (character)} 12 | 13 | \item{secret}{The scret for the Twitter-API (character)} 14 | } 15 | \value{ 16 | OAuth token 17 | } 18 | \description{ 19 | Creates oAuth token for Twitter-API Access and returns token 20 | } 21 | \examples{ 22 | #makeOAuth() 23 | 24 | } 25 | 26 | -------------------------------------------------------------------------------- /man/operatorValuePair.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/regexBuilder.R 3 | \name{operatorValuePair} 4 | \alias{operatorValuePair} 5 | \title{operatorValuePair} 6 | \usage{ 7 | operatorValuePair(key, value) 8 | } 9 | \arguments{ 10 | \item{key}{of the key/value pair. Is always a mongo operator like $regex} 11 | 12 | \item{value}{of the key/value pair. Can be the regex and/or the corresponding option.} 13 | } 14 | \value{ 15 | operator value pair 16 | } 17 | \description{ 18 | Creates operator value pair, called by buildRegexQuery. 19 | } 20 | \examples{ 21 | #operatorValuePair(c("$regex","$options"),c("koln","i")) 22 | 23 | } 24 | 25 | -------------------------------------------------------------------------------- /man/plotTweets.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/mongoQueries.R 3 | \name{plotTweets} 4 | \alias{plotTweets} 5 | \title{plotTweets} 6 | \usage{ 7 | plotTweets(data, tophashtags, interval) 8 | } 9 | \arguments{ 10 | \item{data}{dataframe to plot created by createTwitterTimeSeries()} 11 | 12 | \item{tophashtags}{number of hashtags to plot.} 13 | 14 | \item{interval}{specified time interval. Relevant for the x-axis of the plot.} 15 | } 16 | \value{ 17 | plot of the given dataframe 18 | } 19 | \description{ 20 | Plots a dataframe in order to visualize the sum of hashtags in a 21 | given time interval. 22 | } 23 | \examples{ 24 | #plots the top 10 hashtags 25 | #plotTweets(data,10) 26 | #interval <- createIntervalVector(c("2016-01-15 20:00:00", "2016-01-16 00:10:00"),9) 27 | #interval 28 | #plotTweets(data,10, interval) 29 | } 30 | 31 | -------------------------------------------------------------------------------- /man/rankTweets.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/mongoQueries.R 3 | \name{rankTweets} 4 | \alias{rankTweets} 5 | \title{rankTweets} 6 | \usage{ 7 | rankTweets(data) 8 | } 9 | \arguments{ 10 | \item{data}{dataframe time series to rank.} 11 | } 12 | \value{ 13 | dataframe consisting of ranked hashtags 14 | } 15 | \description{ 16 | Ranks the hashtags according to their respective counts. Highest 17 | count in a given interval is being assigned rank 1. Second highest 18 | counts rank 2 and so on. 19 | } 20 | \examples{ 21 | #rankTweets(dataframe) 22 | } 23 | 24 | -------------------------------------------------------------------------------- /man/setAPICredentials.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/authentification.R 3 | \name{setAPICredentials} 4 | \alias{setAPICredentials} 5 | \title{Store Twitter-API Credentials} 6 | \usage{ 7 | setAPICredentials(key, secret) 8 | } 9 | \arguments{ 10 | \item{key}{The key for the Twitter-API: Consumer Key (API Key)} 11 | 12 | \item{secret}{The scret for the Twitter-API: Consumer Secret (API Secret)} 13 | } 14 | \value{ 15 | None 16 | } 17 | \description{ 18 | This function stores you Twitter-API key and secret to make it available for other functions and 19 | for other instances of R. 20 | } 21 | \examples{ 22 | setAPICredentials(key = "Consumer Key", secret = "Consumer Secret") 23 | 24 | } 25 | 26 | -------------------------------------------------------------------------------- /man/setMongoDbCredentials.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/mongoConnection.R 3 | \name{setMongoDbCredentials} 4 | \alias{setMongoDbCredentials} 5 | \title{Set MongoDB Credentials} 6 | \usage{ 7 | setMongoDbCredentials(type, collection, db, url) 8 | } 9 | \arguments{ 10 | \item{type}{Type to set the MongoDB credentials for: hometimeline or filterstream} 11 | 12 | \item{collection}{The collection to store the tweets in} 13 | 14 | \item{db}{The database to store the tweets in} 15 | 16 | \item{url}{The path to the MongoDB} 17 | } 18 | \value{ 19 | None 20 | } 21 | \description{ 22 | Function to set MongoDB credentials. Type can be hometimeline or filterstream. 23 | Creates either hometimeline or filterstream as a connection element. 24 | } 25 | \examples{ 26 | setMongoDbCredentials (type = "hometimeline", collection = "hometimeline", 27 | db = "twitter", url = "mongodb://localhost") 28 | 29 | } 30 | 31 | -------------------------------------------------------------------------------- /man/startStreaming.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/filterstream.R 3 | \name{startStreaming} 4 | \alias{startStreaming} 5 | \title{Start streaming} 6 | \usage{ 7 | startStreaming(timeout = 60, query_url) 8 | } 9 | \arguments{ 10 | \item{timeout}{period of time after which the stream ist stopped 11 | and restarted with a updated list of search parameters} 12 | 13 | \item{query_url}{set a specific URL to query the API} 14 | } 15 | \value{ 16 | list of hashtags 17 | } 18 | \description{ 19 | Start the streaming process for the filterstream 20 | in a seperate R process. The timeout also defines the maximum waiting time 21 | between executing \link{stopStreaming} and the end of the streaming process 22 | If no query_url is supplied then the topHashtags from the users hometimeline 23 | are used. 24 | } 25 | \examples{ 26 | #startStreaming(320) 27 | #startStreaming(60,"https://stream.twitter.com/1.1/statuses/filter.json?track=Trump") 28 | 29 | } 30 | 31 | -------------------------------------------------------------------------------- /man/stopStreaming.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/filterstream.R 3 | \name{stopStreaming} 4 | \alias{stopStreaming} 5 | \title{Stop streaming} 6 | \usage{ 7 | stopStreaming() 8 | } 9 | \value{ 10 | list of hashtags 11 | } 12 | \description{ 13 | Stop the streaming process. Streaming is stoped within the timeframe given 14 | as timeout in \link{startStreaming} 15 | Stop stream will not terminate the streaming process imediately but stop instead 16 | } 17 | \examples{ 18 | #stopStreaming() 19 | 20 | } 21 | 22 | -------------------------------------------------------------------------------- /man/streamingLoop.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/filterstream.R 3 | \name{streamingLoop} 4 | \alias{streamingLoop} 5 | \title{StreamingLoop} 6 | \usage{ 7 | streamingLoop(timeout = 30, type, createLog = TRUE) 8 | } 9 | \arguments{ 10 | \item{timeout}{Time until the streaming is stoped and restarted with updated parameters} 11 | 12 | \item{type}{The type of stream which is started. (1=Based on hometimeline) (2=Based on query_url)} 13 | 14 | \item{createLog}{If set to FALSE output is send to the console instead of the logfile 15 | (logfile_filterstream.txt)} 16 | } 17 | \description{ 18 | StreamingLoop is usually started by \link{startStreaming} in a seperate instance of R. 19 | If you start StreamingLoop manually, you will not be able to stop it using R. StreamingLoop 20 | can be triggered to stop after timeout using \link{stopStreaming}. 21 | } 22 | \examples{ 23 | #do not run 24 | #streamingLoop() 25 | 26 | } 27 | 28 | -------------------------------------------------------------------------------- /man/topHashtagsInInterval.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/dateOperation.R 3 | \name{topHashtagsInInterval} 4 | \alias{topHashtagsInInterval} 5 | \title{Top Hashtags in intervall} 6 | \usage{ 7 | topHashtagsInInterval(mongo, interval, amount = 10) 8 | } 9 | \arguments{ 10 | \item{mongo}{a mongoDB connection to use (default: hometimeline)} 11 | 12 | \item{interval}{a time interval which can be generated by \link{getInterval} needs to be in unix timestamp format} 13 | 14 | \item{amount}{limits the number of hashtags returned} 15 | } 16 | \value{ 17 | list of hashtags 18 | } 19 | \description{ 20 | Retrives the most used hashtags in a given time interval 21 | } 22 | \examples{ 23 | #topHashtagsInInterval(hometimeline, interval = getInterval(60*24), 10) 24 | #or alternatively specify interval beforehand 25 | #timeframe <- c("2016-01-04 18:37:43 CET","2016-01-05 18:37:43 CET") 26 | #hashtags <- topHashtagsInInterval(hometimeline, interval = 27 | #getInterval(inputinterval = timeframe), 10) 28 | 29 | } 30 | 31 | -------------------------------------------------------------------------------- /man/updateHometimeline.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/hometimeline.R 3 | \name{updateHometimeline} 4 | \alias{updateHometimeline} 5 | \title{Update Home Timeline} 6 | \usage{ 7 | updateHometimeline(connection = "hometimeline", oAuth = makeOAuth()) 8 | } 9 | \arguments{ 10 | \item{connection}{a mongoconnection to use (default: hometimeline)} 11 | 12 | \item{oAuth}{an oAuth token to use, by default a token is retrived by using \link{makeOAuth}} 13 | } 14 | \value{ 15 | None 16 | } 17 | \description{ 18 | Function to retrive and update the home timeline, the home timeline consist of up to 800 tweets 19 | posted by the accounts the user follows. Set Sys.setlocale("LC_TIME", "English") in order 20 | to be able to correctly process the twitter timestamp. See ?as.POSIXct for help. 21 | } 22 | \examples{ 23 | #updateHometimeline() 24 | 25 | } 26 | 27 | -------------------------------------------------------------------------------- /man/useConjunction.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/regexBuilder.R 3 | \name{useConjunction} 4 | \alias{useConjunction} 5 | \title{useConjunction} 6 | \usage{ 7 | useConjunction(firstpart, secondpart, conjunction) 8 | } 9 | \arguments{ 10 | \item{firstpart}{first part of the query} 11 | 12 | \item{secondpart}{second part of the query} 13 | 14 | \item{conjunction}{which can only be "$and" or "$or"} 15 | } 16 | \value{ 17 | linked mongo query parts. 18 | } 19 | \description{ 20 | Connects query parts with either $and or $or. 21 | } 22 | \examples{ 23 | useConjunction(c("$regex","$options"),c("syrien","i"),"$and") 24 | } 25 | 26 | -------------------------------------------------------------------------------- /vignettes/TwitteR2Mongo.Rmd: -------------------------------------------------------------------------------- 1 | --- 2 | title: "TwitteR2Mongo" 3 | author: "Philipp Prettl and Lion Weber" 4 | date: "`r Sys.Date()`" 5 | output: rmarkdown::html_vignette 6 | vignette: > 7 | %\VignetteIndexEntry{TwitteR2Mongo} 8 | %\VignetteEngine{knitr::rmarkdown} 9 | %\VignetteEncoding{UTF-8} 10 | --- 11 | 12 | ## Introduction 13 | 14 | We are happy to introduce our new package TwitteR2Mongo connecting the Twitter API to the MongoDB using R. To ease storing and processing of large ammonuts of tweets we use the MongoDB to store the tweets in different collections. Using this package it is possible to find the most common hashtags based on your personal network i.e. the people you follow on twitter. These hashtags can be used to track the topics and trends relevant in your personal network. 15 | 16 | The package accesses two different types of API 17 | 18 | - The REST API to pull the hometimeline of the user 19 | - The Streaming API to filter all tweets posted on twitter on relevant keywords 20 | 21 | The relevant keywords for the Streaming API are gererated using the information from the hometimeline so all tweets with content relevant to the network observed are stored. These keywords are updated dynamically when new tweets appear on the hometimeline. Alternatively you can specify a query for the Twitter Streaming API and stream those. 22 | 23 | 24 | ## Getting Started 25 | 26 | To use this package a working mongoDB installation is required. You can start the MongoDB server by running: 27 | 28 | ``` 29 | mongod 30 | ``` 31 | 32 | If it is the first time you start the MongoDB server you need to create a writeable directory `C:/data/db` (Windows). For a local MongoDB installation the following information should be sufficient. 33 | 34 | ```r 35 | # Load the package 36 | library(TwitteR2Mongo) 37 | # Specify the two collections to use for storing the tweets 38 | setMongoDbCredentials(type = "hometimeline", collection = "hometimeline", db = "twitter", 39 | url = "mongodb://localhost") 40 | setMongoDbCredentials(type = "filterstream", collection = "filterstream", db = "twitter", 41 | url = "mongodb://localhost") 42 | 43 | # Check the connection 44 | hometimeline <- connect2MongoDb("hometimeline") 45 | filterstream <- connect2MongoDb("filterstream") 46 | 47 | ``` 48 | 49 | Additionally you need a Twitter Account. Using this account you can register a Twitter App at: [Twitter Application Management](https://apps.twitter.com/) and get your Consumer Key (API Key) and Consumer Secret (API Secret). Make sure to set the Callback URL to: `http://127.0.0.1:1410`. 50 | 51 | To connect to the Twitter-API first set your credentials using: 52 | 53 | ```r 54 | setAPICredentials(key = "your-API-KEY", secret = "your-API-SECRET") 55 | makeOAuth() 56 | ``` 57 | 58 | Please use the option to store the oAuth in a file(`.httr-oauth`) as the Streaming will not work without it. 59 | 60 | ## The Hometimeline 61 | 62 | The hometimeline contains up to 800 tweets posted by users you follow. Depending on how many users you 63 | are currently following, you should think about updating your hometimelime regularly. 64 | 65 | ```r 66 | # Create a connection to the collection holding the hometimeline 67 | hometimeline <- connect2MongoDb("hometimeline") 68 | 69 | # Retrive the most recent tweets via updateHometimeline() 70 | updateHometimeline() 71 | 72 | ``` 73 | 74 | 75 | getInterval() returns a unixtimestamp interval. Use Sys.setlocale("LC_TIME","English"), because Twitter provides a timestamp (later the "created _at" field) which needs an English environment to be properly parsed. For details see ?as.POSIXct. If no parameters have been passed on, the function returns an interval corresponding to the last hour. If you want to have an interval which is equivalent to the last 24 hours use getInterval(60*24) (i.e. 60minutes * 24 hours). Additionally you can pass on a vector of date times via inputinterval as shown in the example below. Refrain from using the times 00:00:00 and 12:00:00. They won't be parsed. Use 00:00:01 etc. instead. When working with the twitter API you should keep in mind, that the dates provided are always in GMT. 76 | 77 | ```r 78 | #Set digits to 13 in order see the exact unixtimestamp in ms 79 | options( digits = 13) 80 | 81 | #interval of the last hour 82 | getInterval() 83 | 84 | #interval of the last 24 hours 85 | getInterval(60*24) 86 | 87 | #specified interval 88 | timeframe <- c("2016-01-04 18:37:43 CET","2016-01-05 18:37:43 CET") 89 | getInterval(inputinterval = timeframe) 90 | 91 | ``` 92 | 93 | 94 | Use topHashtagsInInterval() to extract the Top hashtags from your database. 95 | Get the Top 10 hastags in your network within the last 24 hours. 96 | If you want to access the tweets provided by the Streaming API, just 97 | substitute "hometimeline" by "filterstream" in order to access the other collection. 98 | 99 | ```r 100 | topHashtagsInInterval(hometimeline, interval = getInterval(60*24), 10) 101 | 102 | topHashtagsInInterval(hometimeline, interval = getInterval(inputinterval = timeframe), 10) 103 | 104 | ``` 105 | 106 | 107 | 108 | ## The Streaming Process 109 | 110 | The Top hastags are used to filter all tweets on twitter for relevant hashtags. To get these tweets we need to connect to the streaming API. Once started the package will continue to download and import tweets until it is stopped. The streaming process will be started in an additional R process, which handels the streaming process on its own and allows you to keep on working in your current one. The timeout indicates after how many seconds the process is restarted with updated filter parameters. Don't use too low values, otherwise you might be blacklisted by Twitter. You may also stream tweets independent from your hometimeline. You can specify various search queries as shown below. The streaming process can only be stopped by `stopStreaming()`. If a timeout occurs, then the process is not restared with new filter parameters but terminated. The higher the timeout is the longer the maximum waiting time for the process to terminate. 111 | WARNING: The stream may create tens of GB per day and consume a lot of working memory. Execept for testing it is recommended to run it on a seperate computer. Additionally it should have an SSD and you should think about indexing your data. For further information on indexes and why they might be helpful visit: https://docs.mongodb.org/manual/indexes/ . 112 | 113 | ```r 114 | # Start the streaming process 115 | startStreaming(timeout = 300) 116 | 117 | #Start the streaming process with a specified query_url 118 | startStreaming(60,"https://stream.twitter.com/1.1/statuses/filter.json?track=Trump") 119 | 120 | #Get a random sample of all tweets 121 | startStreaming(60,"https://stream.twitter.com/1.1/statuses/sample.json") 122 | 123 | # Stop the streaming process 124 | stopStreaming() 125 | ``` 126 | 127 | 128 | ## Illustrate the most important topics in your hometimeline 129 | 130 | 131 | Extract all hashtags from your mongoDB which have been posted in the time interval specified in createIntervalVector. CreateIntervalVector takes two date time strings in the following format "2016-01-14 23:00:01" or "2016-01-15 08:00:01". You may also use the TwitterAPI format, for example "Thu Jan 15 13:38:00 +0000 2016". It then calculates a time interval specified by the second parameter in the function and returns the corresponding unix timestamps. The example below creates an interval from the 14th of January 23:00:00 to the 15th of January 08:00:00, in hourly steps. 132 | 133 | ```r 134 | createIntervalVector(c("2016-01-14 23:00:01", "2016-01-15 08:00:01"),9) 135 | 136 | # Which corresponds to: 137 | "2016-01-14 23:00:01 CET" "2016-01-15 00:00:01 CET" 138 | "2016-01-15 01:00:01 CET" "2016-01-15 02:00:01 CET" 139 | "2016-01-15 03:00:01 CET" "2016-01-15 04:00:01 CET" 140 | "2016-01-15 05:00:01 CET" "2016-01-15 06:00:01 CET" 141 | "2016-01-15 07:00:01 CET" "2016-01-15 08:00:01 CET" 142 | 143 | ``` 144 | 145 | CreateTwitterTimeseries then queries the mongoDB and extracts all hashtags from the respective time intervals and constructs a data frame. ( Again a warning, if the amount of data is very large, this may take some time.) Additionally rare tweets whose sum during the time interval are below a certain threshold are being removed from the data frame. Afterwards the data frame is being ordered in decreasing fashion with respect to the last column. Then using plotTweets() plots the top x hashtags with respect to the last time interval. The function creates a timeseries via stacking the data frame and converting it into a vectorized representation, and then uses ggplot2 to plot. 146 | 147 | 148 | ```r 149 | timeseries <- createTwitterTimeSeries(filterstream, c("2016-01-14 23:00:01", "2016-01-15 08:00:01"),10) 150 | interval <- createIntervalVector(c("2016-01-14 23:00:01", "2016-01-15 08:00:01"),10) 151 | print(plotTweets(timeseries[2:nrow(timeseries),], 20, interval)) 152 | 153 | ``` 154 | 155 | ![alt text](figure/Timeline.png) 156 | 157 | rankTweets 158 | 159 | If you want to get a ranked representation of your data frame you can use 160 | rankTweets. This presentation ranks your tweets in the respective intervals, which may help to identify if a hashtag has become trending. 161 | 162 | ```r 163 | rankmoving <- rankTweets(timeseries) 164 | head(rankmoving, n = 10) 165 | ``` 166 | 167 | 168 | absoluteHashtagCounts 169 | 170 | If you want to sum up the counts of the respective intervals use absoluteHashtagCounts(). 171 | 172 | ```r 173 | counts <- absoluteHashtagCount(timeseries) 174 | 175 | ``` 176 | 177 | ## BuildRegexQuery 178 | 179 | 180 | The buildRegexQuery function builds a JSON string which allows you to search the mongo fields „entities.hashtags.text“ and „text“ for certain hashtags or words, in a given timeframe you might be interested in. Parameters you can pass on are the regular expression, a timestamp which defines your time interval (you can use getInterval() for that), the fields to be searched, the regex options supported by mongoDB and a conjunction. 181 | 182 | The example below builds a JSON string which looks for the hashtag #Trump in the timeframe 2016-01-15 03:00:01 to 2016-01-15 04:00:01, in the fields “entitites.hashtags.text” and “text”. The conjunction $or ensures that only one of the used regular expressions needs to be found in a tweet in order for the tweet to be returned (In this case we are only looking for one, but you can extend that to many regular expressions). Using the conjunction $and results in returned tweets which have all regular expressions in common. A couple of parameters have a standard input, see ?buildRegexQuery() for more details. 183 | 184 | ```r 185 | interval <- getInterval( inputinterval = c("2016-01-15 03:00:01", "2016-01-15 04:00:01")) 186 | query <- buildRegexQuery(c("Trump"), timestamp = interval) 187 | 188 | ``` 189 | 190 | Now using filterstream$find(query, fields), returns a data frame with tweets containing one of the regular expression hits and the three mongo fields “text”, “entitites.hashtags.text” and “created_at” specified by getMongoFields(). Note: Refrain from using regular expressions with the characters \, [ and ] since these characters are being replaced during the JSON string building process, thus falsifying your regex. Alternatively you can use a dummy like "regextobereplaced" and replace that dummy with a complicated regex after you have used buildRegexQuery(). 191 | 192 | ```r 193 | fields <- getMongoFields(c("text","entitites.hashtags.text","created_at")) 194 | 195 | data <- filterstream$find(query, fields) 196 | ``` 197 | 198 | 199 | ## Tweets on a density map 200 | 201 | You can add the coordinates of the tweets to a density map. This function will only extract the 202 | exact coordinates stored in the geo information of the tweet. 203 | 204 | ```r 205 | data <- extractCoordinates("filterstream", "Trump", 1600) 206 | ``` 207 | One can augment the number of geotagged tweets by using the user-location field. This textfiled is 208 | converted to lon/lat coordinates using the Google API. 209 | 210 | To avoid a cluster of tweets in the "center" of the country one should remove the tweets only containing the name of the country 211 | 212 | ```r 213 | data <- data[data$user$location != "USA", ] 214 | data <- data[data$user$location != "United States", ] 215 | data <- data[data$user$location != "United States of America", ] 216 | 217 | result <- geocodeDataFrame(data) 218 | 219 | drawMap(data = result, location = "USA", zoom = 4, fill = TRUE) 220 | 221 | ``` 222 | 223 | ![alt text](figure/Density.png) 224 | 225 | ## Logfiles 226 | 227 | The Streaming process creates two logfiles, as the seperate R instances can not print information to the console. They might be helpful in case something goes wrong with the streaming and updating process. 228 | The logfiles will be stored in your working directory. 229 | -------------------------------------------------------------------------------- /vignettes/figure/Density.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ProjectTw/TwitteR2Mongo/a5d6a6ea67209c4fb4fe6393740b99c5b4193e71/vignettes/figure/Density.png -------------------------------------------------------------------------------- /vignettes/figure/Timeline.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ProjectTw/TwitteR2Mongo/a5d6a6ea67209c4fb4fe6393740b99c5b4193e71/vignettes/figure/Timeline.png --------------------------------------------------------------------------------