├── .DS_Store ├── DESCRIPTION ├── LICENSE ├── NAMESPACE ├── R ├── .DS_Store ├── extlevel.R ├── extlevels_onecountry.R ├── extractWP.R ├── getWPdatatypes.R ├── getWPdownload.R ├── getWPoptions.R ├── spheatGPS.R ├── spheatGPS_dep.R ├── spheatLookup.R ├── spheatNames.R └── spheatNames_dep.R ├── README.md ├── SpaceheaterExampleBangladesh.png ├── data ├── .DS_Store └── gadm_levels28.RData ├── man ├── extractWP.Rd ├── getWPdatatypes.Rd ├── getWPdownload.Rd ├── getWPoptions.Rd ├── spheatGPS.Rd ├── spheatGPS_dep.Rd ├── spheatLookup.Rd ├── spheatNames.Rd └── spheatNames_dep.Rd └── spaceheater.Rproj /.DS_Store: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nbarsch/spaceheater/5ccada3edd47bb0e1bfd5774df59e774905a6217/.DS_Store -------------------------------------------------------------------------------- /DESCRIPTION: -------------------------------------------------------------------------------- 1 | Package: spaceheater 2 | Type: Package 3 | Title: Spatial Download and Analysis in R 4 | Version: 0.1.0 5 | Author: Neal Thomas Barsch 6 | Maintainer: Neal Thomas Barsch 7 | Description: Downloads and automatically assesses spatial data given a dataset containing any sort of location data (GPS, place names) 8 | License: GPL-3 9 | LazyData: TRUE 10 | Depends: R (>= 3.3.0) 11 | Imports: 12 | httr, 13 | rvest, 14 | maps, 15 | purrr, 16 | raster, 17 | rgdal, 18 | reshape2, 19 | rangeBuilder, 20 | foreach, 21 | stringdist, 22 | stringr, 23 | dplyr, 24 | countrycode, 25 | curl, 26 | sf, 27 | sp 28 | URL: https://github.com/nbarsch/spaceheater 29 | RoxygenNote: 6.0.1 30 | -------------------------------------------------------------------------------- /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 | 635 | Copyright (C) 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 | Copyright (C) 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 | export(spheatNames_dep) 2 | export(spheatNAMES) 3 | export(spheatGPS_dep) 4 | export(spheatGPS) 5 | export(spheatLookup) 6 | export(getWPdatatypes) 7 | export(getWPoptions) 8 | export(getWPdownload) 9 | export(extlevel) 10 | export(extractWP) 11 | 12 | import(crayon) 13 | import(sf) 14 | import(countrycode) 15 | import(foreach) 16 | import(httr) 17 | import(rgdal) 18 | import(rvest) 19 | import(stringdist) 20 | import(sp) 21 | import(stringr) 22 | import(velox) 23 | import(dplyr) 24 | importFrom(maps, map.where) 25 | importFrom(curl,curl_download) 26 | importFrom(curl,handle_setopt) 27 | importFrom(curl,new_handle) 28 | importFrom(purrr,map) 29 | importFrom(purrr,map_df) 30 | importFrom(purrr,set_names) 31 | importFrom(rangeBuilder,standardizeCountry) 32 | importFrom(raster,raster) 33 | importFrom(reshape2,dcast) 34 | importFrom(xml2,xml_attr) 35 | -------------------------------------------------------------------------------- /R/.DS_Store: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nbarsch/spaceheater/5ccada3edd47bb0e1bfd5774df59e774905a6217/R/.DS_Store -------------------------------------------------------------------------------- /R/extlevel.R: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | extlevel <- function(spdataframe, country, 5 | gadmlevel, method, datatype, 6 | options, year) 7 | { 8 | 9 | 10 | ###Space for testing 11 | 12 | 13 | 14 | ###Quick character corrections on gadmlevel 15 | if(is.character(gadmlevel)){ 16 | gadmlevel <- gsub("^ *|(?<= ) | *$", "", gadmlevel, perl = TRUE) 17 | gadmlevel <- tolower(gadmlevel) 18 | 19 | ###Specific levels 20 | if(gadmlevel=="state"){gadmlevel <-"1" } 21 | if(gadmlevel=="province"){gadmlevel <-"1" } 22 | 23 | ###Highest 24 | if(gadmlevel=="country"){gadmlevel <-"0" } 25 | if(gadmlevel=="h"){gadmlevel <-"0" } 26 | if(gadmlevel=="high"){gadmlevel <-"0" } 27 | if(gadmlevel=="highest"){gadmlevel <- "0"} 28 | 29 | ###Lowest 30 | 31 | if(gadmlevel=="village"){gadmlevel <-"lowest" } 32 | if(gadmlevel=="low"){gadmlevel <-"lowest" } 33 | if(gadmlevel=="l"){gadmlevel <-"lowest" } 34 | 35 | if(gadmlevel=="lowest") { 36 | gadm28 <- filter(gadm28, iso3c==country ) 37 | gadmlevel <- as.character(gadm28[1,"level"]) 38 | } 39 | } 40 | if(is.integer(gadmlevel)){gadmlevel <- as.character(gadmlevel)} 41 | 42 | lcl <- as.character(gadmlevel) 43 | 44 | loggy <- FALSE 45 | loggyGADM<- FALSE 46 | shpadown <- FALSE 47 | 48 | 49 | ###Option: if NOT missing country: set country and countryiso 50 | if(!(missing(country))){ 51 | 52 | country <- standardizeCountry(country, fuzzyDist = 25) 53 | countryiso <- invisible(countrycode(country, "country.name", "iso3c")) 54 | } 55 | 56 | 57 | ###Option: if NOT missing spdataframe: set master as spdataframe 58 | if(!(missing(spdataframe))){ 59 | 60 | master <- spdataframe 61 | 62 | ###OPTIONS: If MISSING spdataframe 63 | }else{ 64 | 65 | ###Option: If MISSING spdataframe and NOT missing country: read country gadm and set as master 66 | if(!missing(country)){ 67 | 68 | tryCatch(shapetemp <- sf::st_read(dsn=paste0("gadm",countryiso), 69 | layer=paste0(countryiso,"_adm",lcl), quiet=TRUE), 70 | error=function(err){loggyGADM <-TRUE}) 71 | if(!isTRUE(loggyGADM)){ 72 | master <- as.data.frame(shapetemp) 73 | shpadown <- TRUE 74 | } 75 | 76 | ###Option: If MISSING spdataframe and MISSING country: error message and break 77 | }else{ 78 | cat("You are missing both a spdataset and/or a country. Fix and retry.") 79 | break 80 | } 81 | } 82 | #testing for delete 83 | 84 | ###master exists from here, get iso3c column 85 | mastercolnamesreg <- colnames(master) 86 | mastercolnames <- gsub("^ *|(?<= ) | *$", "", mastercolnamesreg, perl = TRUE) 87 | mastercolnames <- tolower(mastercolnames) 88 | mastercID <- mastercolnames[which(mastercolnames %in% c("iso3c", "iso3n","iso" , "country.name", "countryname", "country name", "country"))] 89 | if(length(mastercID)!=1){ 90 | pcnames <- c("iso3c", "iso3n","iso", "country.name", "countryname", "country name", "country" ) 91 | wpcnames <- which(pcnames %in% mastercID) 92 | take <- pcnames[wpcnames[1]] 93 | }else{ 94 | take <-mastercID 95 | } 96 | if(length(mastercID)==0){ 97 | cat("NO COUNTRY NAME IN DATASET, FIX AND TRY AGAIN.") 98 | break 99 | } 100 | 101 | 102 | ###Not match here 103 | if(take=="iso3n"){ 104 | master$iso3c <- invisible(countrycode(master$iso3n, "iso3n", "iso3c")) 105 | take <- "iso3c" 106 | }else{ 107 | if(take !="iso3c") { 108 | n.iso3c <- which(mastercolnames==take) 109 | master$iso3c <- standardizeCountry(master[,n.iso3c], fuzzyDist = 25) 110 | master$iso3c <- invisible(countrycode(master$iso3c, "country.name", "iso3c")) 111 | take <- "iso3c" 112 | } 113 | } 114 | 115 | 116 | 117 | ###Option: MISSING country and NOT missing spdataframe: set countryiso and country 118 | if(missing(country) & !missing(spdataframe)){ 119 | countryiso <- master[1,"iso3c"] 120 | country <- standardizeCountry(countryiso, fuzzyDist = 25) 121 | } 122 | 123 | 124 | master <- as.data.frame(master) 125 | 126 | tempcountry<- filter(master, iso3c==countryiso) 127 | tempcountryname <- countryiso 128 | tempcountryname <- standardizeCountry(tempcountryname, fuzzyDist = 5) 129 | templocid <- as.character(tempcountry[,paste0("ID_",lcl)]) 130 | u.templocid <- unique(templocid) 131 | nu.templocid <- length(u.templocid) 132 | 133 | ###Get shapefile layer for level 134 | if(file.exists(paste0("gadm", countryiso))){ 135 | tryCatch(shapetemp <- sf::st_read(dsn=paste0("gadm",countryiso), 136 | layer=paste0(countryiso,"_adm",lcl), quiet=TRUE), 137 | error=function(err){loggyGADM <-TRUE}) 138 | }else{loggyGADM <- TRUE} 139 | if(!isTRUE(loggyGADM)){ 140 | 141 | ###Get raster 142 | if(file.exists(paste0(tempcountryname,"_", datatype,"_", paste(options, collapse="_"),"_",year,".tif"))){ 143 | rastemp <- tryCatch(raster(paste0(tempcountryname,"_", datatype,"_", paste(options, collapse="_"),"_",year,".tif")), 144 | error=function(err){loggy <- TRUE}) 145 | n.ras <- length(rastemp) 146 | }else{loggy<-TRUE} 147 | } 148 | 149 | 150 | if(isTRUE(loggyGADM)){ 151 | 152 | 153 | df.tempext <- data.frame(ID_0=as.character(tempcountry[1,"ID_0" ]), 154 | ext=NA, area_a_msq=NA, area_a_kmsq=NA, stringsAsFactors = FALSE 155 | ) 156 | colnames(df.tempext)[colnames(df.tempext)=='ext'] <- paste0(method,"_", datatype,"_", options, "_", year, "_",lcl) 157 | colnames(df.tempext)[colnames(df.tempext)=='area_a_msq'] <- paste0("area_",lcl, "_msq") 158 | colnames(df.tempext)[colnames(df.tempext)=='area_a_kmsq'] <- paste0("area_",lcl, "_kmsq") 159 | return(df.tempext) 160 | } 161 | if(isTRUE(loggy) & !isTRUE(loggyGADM)){ 162 | 163 | 164 | if(as.character(lcl)=="0"){ 165 | sumall <- sum(as.vector(st_area(shapetemp))) 166 | df.tempext <- data.frame( 167 | ID_0=as.character(tempcountry[1,"ID_0" ]), 168 | area_0_msq=sumall, 169 | area_0_kmsq=sumall/1000000, 170 | ext=NA, 171 | stringsAsFactors = FALSE 172 | ) 173 | df.tempext[grep('^ID_', names(df.tempext))] <- lapply(df.tempext[grep('^ID_', names(df.tempext))], as.character) 174 | colnames(df.tempext)[colnames(df.tempext)=='ext'] <- paste0(method,"_", datatype,"_", options, "_", year, "_",lcl) 175 | return(df.tempext) 176 | } 177 | else{ 178 | fil.sftemp <- filter(shapetemp, get(paste0("ID_", lcl)) %in% u.templocid) 179 | 180 | ###Error here because 181 | fil.sftemp$area_a <- st_area(fil.sftemp) 182 | fil.sftemp$area_a <- as.numeric(fil.sftemp$area_a) 183 | tempag <- aggregate(area_a~get(paste0("ID_",lcl)), data=fil.sftemp, FUN=sum) 184 | colnames(tempag)[1] <- paste0("ID_",lcl) 185 | fil.sftemp <- fil.sftemp[,1:(ncol(fil.sftemp)-1)] 186 | fil.sftemp <- left_join(fil.sftemp, tempag) 187 | fil.sftemp$area_a_kmsq <- fil.sftemp$area_a/1000000 188 | colnames(fil.sftemp)[colnames(fil.sftemp)=='area_a'] <- paste0("area_",lcl, "_msq") 189 | colnames(fil.sftemp)[colnames(fil.sftemp)=='area_a_kmsq'] <- paste0("area_",lcl, "_kmsq") 190 | df.tempext <- fil.sftemp[,c("ID_0", paste0("ID_",lcl),paste0("area_",lcl,"_msq"), paste0("area_",lcl,"_kmsq"))] 191 | st_geometry(df.tempext) <- NULL 192 | df.tempext$ext <- NA 193 | df.tempext[grep('^ID_', names(df.tempext))] <- lapply(df.tempext[grep('^ID_', names(df.tempext))], as.character) 194 | 195 | colnames(df.tempext)[colnames(df.tempext)=='ext'] <- paste0(method,"_", datatype,"_", options, "_", year, "_",lcl) 196 | 197 | return(df.tempext) 198 | } 199 | } 200 | if(!isTRUE(loggy) & !isTRUE(loggyGADM)){ 201 | 202 | 203 | 204 | if(method=="SUM"){rastemp[is.na(rastemp)]<-0} 205 | 206 | 207 | vrastemp <- velox(rastemp) 208 | 209 | 210 | if(as.character(lcl)!="0"){ 211 | 212 | 213 | fil.sftemp <- filter(shapetemp, get(paste0("ID_", lcl)) %in% u.templocid) 214 | colnames(fil.sftemp)[colnames(fil.sftemp)=='geometry'] <- paste0("geometry",lcl) 215 | fil.sftemp$area_a <- st_area(fil.sftemp) 216 | fil.sftemp$area_a <- as.numeric(fil.sftemp$area_a) 217 | tempag <- aggregate(area_a~get(paste0("ID_",lcl)), data=fil.sftemp, FUN=sum) 218 | colnames(tempag)[1] <- paste0("ID_",lcl) 219 | fil.sftemp <- fil.sftemp[,1:(ncol(fil.sftemp)-1)] 220 | fil.sftemp <- left_join(fil.sftemp, tempag) 221 | fil.sftemp$area_a_kmsq <- fil.sftemp$area_a/1000000 222 | colnames(fil.sftemp)[colnames(fil.sftemp)=='area_a'] <- paste0("area_",lcl, "_msq") 223 | colnames(fil.sftemp)[colnames(fil.sftemp)=='area_a_kmsq'] <- paste0("area_",lcl, "_kmsq") 224 | df.tempext <- fil.sftemp[,c("ID_0", paste0("ID_",lcl),paste0("area_",lcl,"_msq"), paste0("area_",lcl,"_kmsq"))] 225 | 226 | 227 | ###DOnt think need this, delete colnames(df.tempext)[colnames(df.tempext)=='ID_a'] <- paste0("ID_", lcl) 228 | } 229 | if(as.character(lcl)=="0"){ 230 | 231 | sumall <- sum(as.vector(st_area(shapetemp))) 232 | df.tempext <- data.frame( 233 | ID_0=as.character(tempcountry[1,"ID_0" ]), 234 | area_0_msq=sumall, 235 | area_0_kmsq=sumall/1000000, 236 | stringsAsFactors = FALSE 237 | ) 238 | 239 | } 240 | 241 | reps <- 1 242 | 243 | writeLines(c("", paste0("Extracting ",datatype," for ", tempcountryname, ", ", year) )) 244 | 245 | dfburn <- unique(df.tempext) 246 | dfburn$ext <- NA 247 | 248 | if(lcl=="0" | nu.templocid>20){ 249 | writeLines(c("", paste0("Extracting ",datatype," for ", tempcountryname, ", ", year, ", GADM.org level: ",lcl), "Please wait, large file. May take 5 or more mins to see progress. . . ")) 250 | }else{ 251 | writeLines(c("", paste0("Extracting ",datatype," for ", tempcountryname, ", ", year, ", GADM.org level: ",lcl) )) 252 | } 253 | ###Extraction level loop starts here 254 | for(k in u.templocid){ 255 | 256 | ###TESTING Delete 257 | 258 | ###Cut out one of the polygons or not if only one polygon in shapefile 259 | if(nrow(shapetemp)>1){ 260 | 261 | ###TESTING Delete 262 | 263 | ###NEED DYNAMIC ID NUMBER HERE 264 | single <- filter(shapetemp, get(paste0("ID_", lcl))==k) 265 | 266 | 267 | if(nrow(single)>1){ 268 | grouped <- single %>% 269 | group_by(ID_2) %>% 270 | summarise(geometry = sf::st_union(geometry)) %>% 271 | ungroup() 272 | single <- grouped 273 | } 274 | 275 | }else{ 276 | 277 | ###TESTING Delete 278 | 279 | single <-shapetemp 280 | } 281 | 282 | 283 | 284 | ###TESTING Delete 285 | 286 | 287 | ###Extract in velox (faster) 288 | if((datatype %in% c("Births", "Population", "Pregnancies", "AgeStructures")) | (method %in% c("SUM"))){ 289 | extract <- vrastemp$extract(single, fun=sum) 290 | }else{ 291 | extract <- vrastemp$extract(single,fun=mean) 292 | } 293 | 294 | ###TESTING Delete 295 | 296 | dfburn[reps,"ID_0"] <- as.character(df.loc[1,"ID_0"]) 297 | if(as.character(lcl)!="0"){dfburn[reps,paste0("ID_",as.character(lcl))] <- k} 298 | dfburn[reps,"ext"] <- extract 299 | reps <- reps+1 300 | } 301 | 302 | ###TESTING Delete 303 | 304 | df.tempext <- dfburn 305 | 306 | colnames(df.tempext)[colnames(df.tempext)=='ext'] <- paste0(method,"_", datatype,"_", options, "_", year, "_",lcl) 307 | return(df.tempext) 308 | } 309 | } 310 | 311 | -------------------------------------------------------------------------------- /R/extlevels_onecountry.R: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | extlevel <- function(spdataframe, country, 5 | gadmlevel, method, datatype, 6 | options, year) 7 | { 8 | 9 | 10 | ###Space for testing 11 | 12 | 13 | 14 | ###Quick character corrections on gadmlevel 15 | if(is.character(gadmlevel)){ 16 | gadmlevel <- gsub("^ *|(?<= ) | *$", "", gadmlevel, perl = TRUE) 17 | gadmlevel <- tolower(gadmlevel) 18 | 19 | ###Specific levels 20 | if(gadmlevel=="state"){gadmlevel <-"1" } 21 | if(gadmlevel=="province"){gadmlevel <-"1" } 22 | 23 | ###Highest 24 | if(gadmlevel=="country"){gadmlevel <-"0" } 25 | if(gadmlevel=="h"){gadmlevel <-"0" } 26 | if(gadmlevel=="high"){gadmlevel <-"0" } 27 | if(gadmlevel=="highest"){gadmlevel <- "0"} 28 | 29 | ###Lowest 30 | 31 | if(gadmlevel=="village"){gadmlevel <-"lowest" } 32 | if(gadmlevel=="low"){gadmlevel <-"lowest" } 33 | if(gadmlevel=="l"){gadmlevel <-"lowest" } 34 | 35 | if(gadmlevel=="lowest") { 36 | gadm28 <- filter(gadm28, iso3c==country ) 37 | gadmlevel <- as.character(gadm28[1,"level"]) 38 | } 39 | } 40 | if(is.integer(gadmlevel)){gadmlevel <- as.character(gadmlevel)} 41 | 42 | lcl <- as.character(gadmlevel) 43 | 44 | loggy <- FALSE 45 | loggyGADM<- FALSE 46 | shpadown <- FALSE 47 | 48 | 49 | ###Option: if NOT missing country: set country and countryiso 50 | if(!(missing(country))){ 51 | 52 | country <- standardizeCountry(country, fuzzyDist = 25) 53 | countryiso <- invisible(countrycode(country, "country.name", "iso3c")) 54 | } 55 | 56 | 57 | ###Option: if NOT missing spdataframe: set master as spdataframe 58 | if(!(missing(spdataframe))){ 59 | 60 | master <- spdataframe 61 | 62 | ###OPTIONS: If MISSING spdataframe 63 | }else{ 64 | 65 | ###Option: If MISSING spdataframe and NOT missing country: read country gadm and set as master 66 | if(!missing(country)){ 67 | 68 | tryCatch(shapetemp <- sf::st_read(dsn=paste0("gadm",countryiso), 69 | layer=paste0(countryiso,"_adm",lcl), quiet=TRUE), 70 | error=function(err){loggyGADM <-TRUE}) 71 | if(!isTRUE(loggyGADM)){ 72 | master <- as.data.frame(shapetemp) 73 | shpadown <- TRUE 74 | } 75 | 76 | ###Option: If MISSING spdataframe and MISSING country: error message and break 77 | }else{ 78 | cat("You are missing both a spdataset and/or a country. Fix and retry.") 79 | break 80 | } 81 | } 82 | #testing for delete 83 | 84 | ###master exists from here, get iso3c column 85 | mastercolnamesreg <- colnames(master) 86 | mastercolnames <- gsub("^ *|(?<= ) | *$", "", mastercolnamesreg, perl = TRUE) 87 | mastercolnames <- tolower(mastercolnames) 88 | mastercID <- mastercolnames[which(mastercolnames %in% c("iso3c", "iso3n","iso" , "country.name", "countryname", "country name", "country"))] 89 | if(length(mastercID)!=1){ 90 | pcnames <- c("iso3c", "iso3n","iso", "country.name", "countryname", "country name", "country" ) 91 | wpcnames <- which(pcnames %in% mastercID) 92 | take <- pcnames[wpcnames[1]] 93 | }else{ 94 | take <-mastercID 95 | } 96 | if(length(mastercID)==0){ 97 | cat("NO COUNTRY NAME IN DATASET, FIX AND TRY AGAIN.") 98 | break 99 | } 100 | 101 | 102 | ###Not match here 103 | if(take=="iso3n"){ 104 | master$iso3c <- invisible(countrycode(master$iso3n, "iso3n", "iso3c")) 105 | take <- "iso3c" 106 | }else{ 107 | if(take !="iso3c") { 108 | n.iso3c <- which(mastercolnames==take) 109 | master$iso3c <- standardizeCountry(master[,n.iso3c], fuzzyDist = 25) 110 | master$iso3c <- invisible(countrycode(master$iso3c, "country.name", "iso3c")) 111 | take <- "iso3c" 112 | } 113 | } 114 | 115 | 116 | 117 | ###Option: MISSING country and NOT missing spdataframe: set countryiso and country 118 | if(missing(country) & !missing(spdataframe)){ 119 | countryiso <- master[1,"iso3c"] 120 | country <- standardizeCountry(countryiso, fuzzyDist = 25) 121 | } 122 | 123 | 124 | master <- as.data.frame(master) 125 | 126 | tempcountry<- filter(master, iso3c==countryiso) 127 | tempcountryname <- countryiso 128 | tempcountryname <- standardizeCountry(tempcountryname, fuzzyDist = 5) 129 | templocid <- as.character(tempcountry[,paste0("ID_",lcl)]) 130 | u.templocid <- unique(templocid) 131 | nu.templocid <- length(u.templocid) 132 | 133 | ###Get shapefile layer for level 134 | if(file.exists(paste0("gadm", countryiso))){ 135 | tryCatch(shapetemp <- sf::st_read(dsn=paste0("gadm",countryiso), 136 | layer=paste0(countryiso,"_adm",lcl), quiet=TRUE), 137 | error=function(err){loggyGADM <-TRUE}) 138 | }else{loggyGADM <- TRUE} 139 | if(!isTRUE(loggyGADM)){ 140 | 141 | ###Get raster 142 | if(file.exists(paste0(tempcountryname,"_", datatype,"_", paste(options, collapse="_"),"_",year,".tif"))){ 143 | rastemp <- tryCatch(raster(paste0(tempcountryname,"_", datatype,"_", paste(options, collapse="_"),"_",year,".tif")), 144 | error=function(err){loggy <- TRUE}) 145 | n.ras <- length(rastemp) 146 | }else{loggy<-TRUE} 147 | } 148 | 149 | 150 | if(isTRUE(loggyGADM)){ 151 | 152 | 153 | df.tempext <- data.frame(ID_0=as.character(tempcountry[1,"ID_0" ]), 154 | ext=NA, area_a_msq=NA, area_a_kmsq=NA, stringsAsFactors = FALSE 155 | ) 156 | colnames(df.tempext)[colnames(df.tempext)=='ext'] <- paste0(method,"_", datatype,"_", options, "_", year, "_",lcl) 157 | colnames(df.tempext)[colnames(df.tempext)=='area_a_msq'] <- paste0("area_",lcl, "_msq") 158 | colnames(df.tempext)[colnames(df.tempext)=='area_a_kmsq'] <- paste0("area_",lcl, "_kmsq") 159 | return(df.tempext) 160 | } 161 | if(isTRUE(loggy) & !isTRUE(loggyGADM)){ 162 | 163 | 164 | if(as.character(lcl)=="0"){ 165 | sumall <- sum(as.vector(st_area(shapetemp))) 166 | df.tempext <- data.frame( 167 | ID_0=as.character(tempcountry[1,"ID_0" ]), 168 | area_0_msq=sumall, 169 | area_0_kmsq=sumall/1000000, 170 | ext=NA, 171 | stringsAsFactors = FALSE 172 | ) 173 | df.tempext[grep('^ID_', names(df.tempext))] <- lapply(df.tempext[grep('^ID_', names(df.tempext))], as.character) 174 | colnames(df.tempext)[colnames(df.tempext)=='ext'] <- paste0(method,"_", datatype,"_", options, "_", year, "_",lcl) 175 | return(df.tempext) 176 | } 177 | else{ 178 | fil.sftemp <- filter(shapetemp, get(paste0("ID_", lcl)) %in% u.templocid) 179 | 180 | ###Error here because 181 | fil.sftemp$area_a <- st_area(fil.sftemp) 182 | fil.sftemp$area_a <- as.numeric(fil.sftemp$area_a) 183 | tempag <- aggregate(area_a~get(paste0("ID_",lcl)), data=fil.sftemp, FUN=sum) 184 | colnames(tempag)[1] <- paste0("ID_",lcl) 185 | fil.sftemp <- fil.sftemp[,1:(ncol(fil.sftemp)-1)] 186 | fil.sftemp <- left_join(fil.sftemp, tempag) 187 | fil.sftemp$area_a_kmsq <- fil.sftemp$area_a/1000000 188 | colnames(fil.sftemp)[colnames(fil.sftemp)=='area_a'] <- paste0("area_",lcl, "_msq") 189 | colnames(fil.sftemp)[colnames(fil.sftemp)=='area_a_kmsq'] <- paste0("area_",lcl, "_kmsq") 190 | df.tempext <- fil.sftemp[,c("ID_0", paste0("ID_",lcl),paste0("area_",lcl,"_msq"), paste0("area_",lcl,"_kmsq"))] 191 | st_geometry(df.tempext) <- NULL 192 | df.tempext$ext <- NA 193 | df.tempext[grep('^ID_', names(df.tempext))] <- lapply(df.tempext[grep('^ID_', names(df.tempext))], as.character) 194 | 195 | colnames(df.tempext)[colnames(df.tempext)=='ext'] <- paste0(method,"_", datatype,"_", options, "_", year, "_",lcl) 196 | 197 | return(df.tempext) 198 | } 199 | } 200 | if(!isTRUE(loggy) & !isTRUE(loggyGADM)){ 201 | 202 | 203 | 204 | if(method=="SUM"){rastemp[is.na(rastemp)]<-0} 205 | 206 | 207 | vrastemp <- velox(rastemp) 208 | 209 | 210 | if(as.character(lcl)!="0"){ 211 | 212 | 213 | fil.sftemp <- filter(shapetemp, get(paste0("ID_", lcl)) %in% u.templocid) 214 | colnames(fil.sftemp)[colnames(fil.sftemp)=='geometry'] <- paste0("geometry",lcl) 215 | fil.sftemp$area_a <- st_area(fil.sftemp) 216 | fil.sftemp$area_a <- as.numeric(fil.sftemp$area_a) 217 | tempag <- aggregate(area_a~get(paste0("ID_",lcl)), data=fil.sftemp, FUN=sum) 218 | colnames(tempag)[1] <- paste0("ID_",lcl) 219 | fil.sftemp <- fil.sftemp[,1:(ncol(fil.sftemp)-1)] 220 | fil.sftemp <- left_join(fil.sftemp, tempag) 221 | fil.sftemp$area_a_kmsq <- fil.sftemp$area_a/1000000 222 | colnames(fil.sftemp)[colnames(fil.sftemp)=='area_a'] <- paste0("area_",lcl, "_msq") 223 | colnames(fil.sftemp)[colnames(fil.sftemp)=='area_a_kmsq'] <- paste0("area_",lcl, "_kmsq") 224 | df.tempext <- fil.sftemp[,c("ID_0", paste0("ID_",lcl),paste0("area_",lcl,"_msq"), paste0("area_",lcl,"_kmsq"))] 225 | 226 | 227 | ###DOnt think need this, delete colnames(df.tempext)[colnames(df.tempext)=='ID_a'] <- paste0("ID_", lcl) 228 | } 229 | if(as.character(lcl)=="0"){ 230 | 231 | sumall <- sum(as.vector(st_area(shapetemp))) 232 | df.tempext <- data.frame( 233 | ID_0=as.character(tempcountry[1,"ID_0" ]), 234 | area_0_msq=sumall, 235 | area_0_kmsq=sumall/1000000, 236 | stringsAsFactors = FALSE 237 | ) 238 | 239 | } 240 | 241 | reps <- 1 242 | 243 | writeLines(c("", paste0("Extracting ",datatype," for ", tempcountryname, ", ", year) )) 244 | 245 | dfburn <- unique(df.tempext) 246 | dfburn$ext <- NA 247 | 248 | if(lcl=="0" | nu.templocid>20){ 249 | writeLines(c("", paste0("Extracting ",datatype," for ", tempcountryname, ", ", year, ", GADM.org level: ",lcl), "Please wait, large file. May take 5 or more mins to see progress. . . ")) 250 | }else{ 251 | writeLines(c("", paste0("Extracting ",datatype," for ", tempcountryname, ", ", year, ", GADM.org level: ",lcl) )) 252 | } 253 | ###Extraction level loop starts here 254 | for(k in u.templocid){ 255 | 256 | ###TESTING Delete 257 | 258 | ###Cut out one of the polygons or not if only one polygon in shapefile 259 | if(nrow(shapetemp)>1){ 260 | 261 | ###TESTING Delete 262 | 263 | ###NEED DYNAMIC ID NUMBER HERE 264 | single <- filter(shapetemp, get(paste0("ID_", lcl))==k) 265 | 266 | 267 | if(nrow(single)>1){ 268 | grouped <- single %>% 269 | group_by(ID_2) %>% 270 | summarise(geometry = sf::st_union(geometry)) %>% 271 | ungroup() 272 | single <- grouped 273 | } 274 | 275 | }else{ 276 | 277 | ###TESTING Delete 278 | 279 | single <-shapetemp 280 | } 281 | 282 | 283 | 284 | ###TESTING Delete 285 | 286 | 287 | ###Extract in velox (faster) 288 | if((datatype %in% c("Births", "Population", "Pregnancies", "AgeStructures")) | (method %in% c("SUM"))){ 289 | extract <- vrastemp$extract(single, fun=sum) 290 | }else{ 291 | extract <- vrastemp$extract(single,fun=mean) 292 | } 293 | 294 | ###TESTING Delete 295 | 296 | dfburn[reps,"ID_0"] <- as.character(df.loc[1,"ID_0"]) 297 | if(as.character(lcl)!="0"){dfburn[reps,paste0("ID_",as.character(lcl))] <- k} 298 | dfburn[reps,"ext"] <- extract 299 | reps <- reps+1 300 | } 301 | 302 | ###TESTING Delete 303 | 304 | df.tempext <- dfburn 305 | 306 | colnames(df.tempext)[colnames(df.tempext)=='ext'] <- paste0(method,"_", datatype,"_", options, "_", year, "_",lcl) 307 | return(df.tempext) 308 | } 309 | } 310 | 311 | -------------------------------------------------------------------------------- /R/extractWP.R: -------------------------------------------------------------------------------- 1 | #' 2 | #' Extract WorldPop UK Raster Sets for all locations from a spheated dataset. 3 | #' 4 | #' You must have run an spheat function (spheatNAMES, spheatGPS, or spheatLOOKUP) 5 | #' to exercise this function. 6 | #' 7 | #' @param datatype (character), the datatype you would like to see what options 8 | #' are available for WorldPop UK data. The available datatypes can be attained 9 | #' with the function getWPdatatypes() Example datatypes: \code{“Population”} or 10 | #' \code{“Stunting”} 11 | #' @param options (character), the options of the tif dataset you would like to 12 | #' download. The available options can be attained with the function 13 | #' getWPoptions() e.g. \code{“ppp”} or \code{c(“F”, "interdecile")} 14 | #' @param year (numeric), the year of the dataset you would like to download. 15 | #' Available years are given by the getWPoptions() function for any given country. 16 | #' @param gadmlevel (integer or character), either an integer level gadm level to extract for all countries in MASTERout, or one of 17 | #' \code{gadmlevel="lowest"} for the lowest respective gadm level available 18 | #' or \code{gadmlevel="lcl"} for lowest COMMON level among all countries in MASTERout. 19 | #' Default is \code{gadmlevel="lowest"} 20 | #' @param fill (logical), if extraction values for all higher gadm geographic level values should also be returned. 21 | #' I.e. if gadmlevel=3 and fill=TRUE, extractWP will return the extraction values for gadm levels 0, 1, 2, and 3. 22 | #' If fill=FALSE in this case, extractWP will only return extraction values for gadm level 3. 23 | #' See gadm.org for details about levels (in short level 0 is always country, 1 is state/province/equivalent, 24 | #' 2 is county/municipality/equivalent, 3 is village/equivalent, 4 and more get into blocks and other lower geographic levels). 25 | #' Default is \code{fill=TRUE} 26 | #' @param deleteRAST (logical), logical if the downloaded WorldPop UK Raster sets should be deleted when they are done being analyzed. 27 | #' Reccomended TRUE for datasets containing many countries as TRUE deletes the done analyzed raster 28 | #' before a new one is downloaded, minimizing disk space use. 29 | #' Default is \code{deleteRAST=TRUE} 30 | 31 | #' 32 | #' @author Neal Thomas Barsch 33 | #' @references GADM DATA are attained through the GADM project website. 34 | #' Commercial use of this function is not allowed without prior permission from 35 | #' GADM.org. \url{http://gadm.org/}. 36 | #' 37 | #' 38 | #' @references WorldPop UK data are attained through the WorldPop UK website. 39 | #' These data are licensensed under the Creative Commons Attribution 4.0 40 | #' License. \url{http://www.worldpop.org.uk/}. 41 | #' 42 | #' Eternal grattitude to StackOverflow member hrbrmstr who contributed crucially 43 | #' to the code for the downloads from WorldPop. 44 | #' 45 | #' 46 | #' @examples 47 | #' 48 | #' extractWP(datatype="Births", options="pp", year=2015, gadmlevel="lowest", fill=TRUE, deleteRAST=TRUE) 49 | #' 50 | #' extractWP(datatype="Population", options=c("ppp", "adj"), year=2010, gadmlevel="lowest", fill=TRUE, deleteRAST=TRUE) 51 | #' 52 | #' #You dont want to delete the Raster files (warning, could take a lot of storage space if not deleted) 53 | #' extractWP(datatype="Births", options="pp", year=2015,deleteRAST=FALSE) 54 | #' 55 | #' 56 | #' @export extractWP 57 | 58 | 59 | extractWP <- function(datatype, options, year, gadmlevel="lowest", fill=TRUE, 60 | deleteRAST=TRUE, outdata=MASTERout, geolist=MASTERgeo) 61 | { 62 | 63 | ###Objective here is to take extlevel and make it uniform for other raster layers 64 | ###AND FILL IN ALL COUNTRIES NOT JUST ONE 65 | 66 | 67 | ###Housekeeping 68 | if(is.character(gadmlevel)){ 69 | gadmlevel <- tolower(gadmlevel) 70 | if(gadmlevel=="village"){gadmlevel <-"lowest" } 71 | if(gadmlevel=="state"){gadmlevel <-1 } 72 | if(gadmlevel=="province"){gadmlevel <-1 } 73 | if(gadmlevel=="low"){gadmlevel <-"lowest" } 74 | if(gadmlevel=="l"){gadmlevel <-"lowest" } 75 | if(gadmlevel=="h"){gadmlevel <-0 } 76 | if(gadmlevel=="high"){gadmlevel <-0 } 77 | if(gadmlevel=="country"){gadmlevel <-0 } 78 | if(gadmlevel=="highest"){gadmlevel <- 0} 79 | if(gadmlevel=="lowestcommon"){gadmlevel <- "lcl"} 80 | if(gadmlevel=="lowest common"){gadmlevel <- "lcl"} 81 | if(gadmlevel=="lc"){gadmlevel <- "lcl"} 82 | if(gadmlevel=="common"){gadmlevel <- "lcl"} 83 | 84 | 85 | 86 | if(gadmlevel=="lcl" | gadmlevel=="lowest") { 87 | load("gadm_levels28.RData") 88 | gadm_levels2 <- gadm_levels2[,c("iso3c", "level")] 89 | ### deleted gadm_levels2[grep('iso3c', names(gadm_levels2))] <- lapply(gadm_levels2[grep('iso3c', names(gadm_levels2))], as.character) 90 | } 91 | 92 | if(gadmlevel=="lcl"){ 93 | uni.loc <- as.data.frame(unique(outdata[,"sp_iso3c"])) 94 | colnames(uni.loc)<- "iso3c" 95 | uni.loc <- suppressWarnings(left_join(uni.loc, gadm_levels2)) 96 | gadmlevel <- min(uni.loc$level) 97 | } 98 | 99 | } 100 | 101 | 102 | 103 | 104 | 105 | ###Set METHOD for WP datatype 106 | if(datatype %in% c("Births", "Population", "Pregnancies", "AgeStructures", "SUM")){ 107 | method <- "SUM" 108 | }else{ 109 | method <- "MEAN" 110 | } 111 | 112 | n.geolist <- length(geolist) 113 | 114 | fmax <- function(dat){ 115 | nm1 <- grep("ID", names(dat), value = TRUE) 116 | stopifnot(length(nm1) > 0) 117 | max(as.numeric(gsub("\\D+", "", nm1))) 118 | } 119 | 120 | if(isTRUE(fill)){n.geolist <- length(geolist) 121 | }else{n.geolist <-1} 122 | x2 <- list() 123 | foreach(v=1:length(geolist))%do%{ 124 | n.lgg <- length(geolist[[v]]) 125 | CountryName <- as.character(geolist[[v]][[n.lgg]][1,"CountryName"]) 126 | loggyras <- FALSE 127 | ###download raster here 128 | tempexists <- file.exists(paste0(CountryName,"_", datatype,"_", paste(options, collapse="_"),"_",year,".tif")) 129 | if(!isTRUE(tempexists)){ 130 | ds.wp <- tryCatch(getWPdownload(country=CountryName, datatype=datatype, options=options, year=year), 131 | error=function(ee){ tempexists<- FALSE }) 132 | } 133 | tempexists <- file.exists(paste0(CountryName,"_", datatype,"_", paste(options, collapse="_"),"_",year,".tif")) 134 | if(isTRUE(tempexists)){ 135 | rastemp <- tryCatch(raster(paste0(CountryName,"_", datatype,"_", paste(options, collapse="_"),"_",year,".tif")), 136 | error=function(err){loggyras <- TRUE}) 137 | n.ras <- length(rastemp) 138 | vrastemp <- velox(rastemp) 139 | }else{loggyras<-TRUE} 140 | if(!isTRUE(loggyras)){ 141 | 142 | 143 | 144 | 145 | nv.geosub <- length(geolist[[v]])-1 146 | if(is.character(gadmlevel)){ 147 | gadmlevel <- nv.geosub 148 | } 149 | skip <- 0 150 | if(gadmlevel!=nv.geosub){ 151 | skip <- (nv.geosub-gadmlevel) 152 | start <- skip+1 153 | glist <- list() 154 | each <-1 155 | foreach(s=start:length(geolist[[v]]))%do%{ 156 | glist[[each]] <- geolist[[v]][[s]] 157 | ###geolist[[v]][[s]] <- NULL 158 | each <- each+1 159 | } 160 | } 161 | 162 | #### if(gadmlevel!=lgeosub){gadmlevel} 163 | 164 | if(isTRUE(fill)){ 165 | nv.geolist <- length(geolist[[v]]) 166 | }else{nv.geolist <-1} 167 | tx2 <- list() 168 | rgadmlevel <- gadmlevel 169 | foreach(q=1:nv.geolist)%do%{ 170 | r <- length(geolist)-rgadmlevel 171 | tframe <- as.data.frame(geolist[[v]][[r]]) 172 | n.tframe <- nrow(tframe) 173 | maxID <- fmax(tframe) 174 | sub.tframe <- tframe[,c(paste0("ID_",maxID), paste0("geometry",maxID))] 175 | if(method=="SUM"){ 176 | sub.tframe$ext <- as.numeric(vrastemp$extract(sub.tframe[,paste0("geometry",maxID)], fun=function(x){sum(x, na.rm=TRUE)})) 177 | } 178 | if(method=="MEAN"){ 179 | sub.tframe$ext <- as.numeric(vrastemp$extract(sub.tframe[,paste0("geometry",maxID)], fun=function(x){mean(x, na.rm=TRUE)})) 180 | } 181 | ### maxID also length(geolist[[v]])-q 182 | sub.tframe <- sub.tframe[, c(1,3)] 183 | colnames(sub.tframe)[colnames(sub.tframe)=='ext'] <- paste0(method,"_", datatype,"_", paste(options, collapse="_"), "_", year, "_",maxID) 184 | drops <- c(paste0("geometry",maxID)) 185 | tframe <- tframe[ , !(names(tframe) %in% drops)] 186 | tframe <- left_join(tframe, sub.tframe) 187 | tx2[[q]] <- tframe 188 | rgadmlevel <- rgadmlevel-1 189 | } 190 | x2[[v]]<-tx2 191 | if(isTRUE(deleteRAST)){ 192 | file.remove(paste0(CountryName,"_", datatype,"_", paste(options, collapse="_"),"_",year,".tif")) 193 | } 194 | } 195 | } 196 | MASTERextract <- list() 197 | foreach(p=1:length(x2))%do%{ 198 | MASTERextract[[p]] <- suppressMessages(Reduce(left_join, x2[[p]])) 199 | } 200 | MASTERextract <- suppressWarnings(do.call("bind_rows", MASTERextract)) 201 | colnames(MASTERextract) <- paste("sp", colnames(MASTERextract), sep="_") 202 | MASTERextract <<- MASTERextract 203 | MASTERbackout1 <<- outdata 204 | MASTERout <<- suppressMessages(left_join(outdata, MASTERextract)) 205 | cat("Done. MASTERout updated. MASTERextract created. Not available=NA. ") 206 | } 207 | -------------------------------------------------------------------------------- /R/getWPdatatypes.R: -------------------------------------------------------------------------------- 1 | #' Get the available datatypes for a country from WorldPop UK datasets 2 | #' 3 | #' This function pulls what are the available datatypes from WorldPop UK for a 4 | #' given country. It returns a not available message if the country typed does 5 | #' not exist on WorldPop. As a bonus and to make matching WorldPop sets easier, 6 | #' this function contains correction algorithms to standardize country names to 7 | #' match WorldPop UK sets (i.e. WorldPop has "Côte d'Ivoire", you can type 8 | #' "Ivory Coast" and it will return the WorldPop Côte d'Ivoire set). This 9 | #' function adds a dataframe of the available sets called WPdata.types to your 10 | #' working environment. 11 | #' 12 | #' 13 | #' @param countryname (character), the name of a country you want to see what 14 | #' data is avaialble from WorldPop for. e.g. \code{“Tanzania”} 15 | #' @author Neal Thomas Barsch 16 | #' @references WorldPop UK data are attained through the WorldPop UK website. 17 | #' These data are licensensed under the Creative Commons Attribution 4.0 18 | #' License. \url{http://www.worldpop.org.uk/}. 19 | #' 20 | #' Eternal grattitude to StackOverflow member hrbrmstr without whom this 21 | #' function would not have been possible. 22 | #' @examples 23 | #' 24 | #' 25 | #' getWPdatatypes("Nigeria") 26 | #' 27 | #' @export getWPdatatypes 28 | getWPdatatypes <- function (country) { 29 | ###standardize country name, takes care of stuff like Bolivia (Plurinational State of) or tildes like Côte d'Ivoire 30 | country <- standardizeCountry(paste(country),fuzzyDist=30) 31 | 32 | 33 | # Need to "prime" the session with a cookie 34 | res <- GET(url="http://www.worldpop.org.uk/data/data_sources/") 35 | # Get the page contents 36 | pg <- content(res) 37 | # Find the summary links 38 | summary_link_nodes <- html_nodes(pg, xpath=".//a[contains(@href,'summary')]") 39 | map(summary_link_nodes, html_nodes, xpath=".//../..") %>% 40 | map(html_children) %>% 41 | map(html_text) %>% 42 | map(~.[1:4]) %>% 43 | map(as.list) %>% 44 | map_df(set_names, c("continent", "country", "resolution", "data_type")) %>% 45 | bind_cols( 46 | data_frame( 47 | summary_link = sprintf("http://www.worldpop.org.uk%s", html_attr(summary_link_nodes, "href")) 48 | ) 49 | ) -> world_pop_data 50 | world_pop_data$data_type <- gsub("Urban change", "UrbanChange", world_pop_data$data_type) 51 | world_pop_data$data_type <- gsub("Maternal and Newborn Health", "MaternalNewbornHealth", world_pop_data$data_type) 52 | world_pop_data$data_type <- gsub("Contraceptive Use", "ContraceptiveUse", world_pop_data$data_type) 53 | world_pop_data$data_type <- gsub("Age structures", "AgeStructures", world_pop_data$data_type) 54 | world_pop_data$data_type <- gsub("Dynamic Population", "DynamicPopulation", world_pop_data$data_type) 55 | countryreference <- as.data.frame(world_pop_data) 56 | countryreference <- countryreference[,c(1,2,4)] 57 | countryreference <- countryreference[!(countryreference$country)=="N/A",] 58 | world_pop_data <- world_pop_data[!(world_pop_data$country)=="N/A",] 59 | 60 | ###Filter country names so they match the desired country 61 | ###There is probably a better way to do this but I had this code from standardizing country name lists for matching a while back 62 | countryreference$CountryStandard <- standardizeCountry(countryreference[,"country"], fuzzyDist=20) 63 | countryreference$CountryEdit <- gsub("[()]", "", countryreference$country) 64 | countryreference$CountryEdit2 <- gsub("\\s*\\([^\\)]+\\)","",as.character(countryreference$country)) 65 | foreach(a=1:nrow(countryreference)) %do% { 66 | if(countryreference[a,"CountryStandard"]==""){ 67 | countryreference[a,"CountryStandard"] <- standardizeCountry(countryreference[a,"CountryEdit"], fuzzyDist=20) 68 | if(countryreference[a,"CountryStandard"]==""){ 69 | countryreference[a,"CountryStandard"] <- standardizeCountry(countryreference[a,"CountryEdit2"], fuzzyDist=20) 70 | if(countryreference[a,"CountryStandard"]==""){ 71 | countryreference[a,"CountryStandard"] <- toupper(countryreference[a,"country"]) 72 | } 73 | } 74 | } 75 | } 76 | exists <- isTRUE(paste(country) %in% as.character(countryreference$CountryStandard)) 77 | if(exists==FALSE){ 78 | print("It appears this country is not in the WorldPop set, please check and try again") 79 | return("nodata") 80 | } 81 | countryreference <- countryreference[,c(1,4,3)] 82 | world_pop_data$CountryStandard <- countryreference[,2] 83 | world_pop_data <- world_pop_data[,c(1,6,2,3,4,5)] 84 | countryreference <- suppressMessages(dcast(countryreference, continent+CountryStandard ~ data_type)) 85 | countryreference <- filter(countryreference, countryreference$CountryStandard==country) 86 | countryreference <- countryreference[,colSums(is.na(countryreference))% 87 | map(html_children) %>% 88 | map(html_text) %>% 89 | map(~.[1:4]) %>% 90 | map(as.list) %>% 91 | map_df(set_names, c("continent", "country", "resolution", "data_type")) %>% 92 | bind_cols( 93 | data_frame( 94 | summary_link = sprintf("http://www.worldpop.org.uk%s", html_attr(summary_link_nodes, "href")) 95 | ) 96 | ) -> world_pop_data 97 | world_pop_data$data_type <- gsub("Urban change", "UrbanChange", world_pop_data$data_type) 98 | world_pop_data$data_type <- gsub("Maternal and Newborn Health", "MaternalNewbornHealth", world_pop_data$data_type) 99 | world_pop_data$data_type <- gsub("Contraceptive Use", "ContraceptiveUse", world_pop_data$data_type) 100 | world_pop_data$data_type <- gsub("Age structures", "AgeStructures", world_pop_data$data_type) 101 | world_pop_data$data_type <- gsub("Dynamic Population", "DynamicPopulation", world_pop_data$data_type) 102 | countryreference <- as.data.frame(world_pop_data) 103 | countryreference <- countryreference[,c(1,2,4)] 104 | countryreference <- countryreference[!(countryreference$country)=="N/A",] 105 | world_pop_data <- world_pop_data[!(world_pop_data$country)=="N/A",] 106 | 107 | ###Filter country names so they match the desired country 108 | ###There is probably a better way to do this but I had this code from standardizing country name lists for matching a while back 109 | countryreference$CountryStandard <- standardizeCountry(countryreference[,"country"], fuzzyDist=20) 110 | countryreference$CountryEdit <- gsub("[()]", "", countryreference$country) 111 | countryreference$CountryEdit2 <- gsub("\\s*\\([^\\)]+\\)","",as.character(countryreference$country)) 112 | foreach(a=1:nrow(countryreference)) %do% { 113 | if(countryreference[a,"CountryStandard"]==""){ 114 | countryreference[a,"CountryStandard"] <- standardizeCountry(countryreference[a,"CountryEdit"], fuzzyDist=20) 115 | if(countryreference[a,"CountryStandard"]==""){ 116 | countryreference[a,"CountryStandard"] <- standardizeCountry(countryreference[a,"CountryEdit2"], fuzzyDist=20) 117 | if(countryreference[a,"CountryStandard"]==""){ 118 | countryreference[a,"CountryStandard"] <- toupper(countryreference[a,"country"]) 119 | } 120 | } 121 | } 122 | } 123 | exists <- isTRUE(paste(country) %in% as.character(countryreference$CountryStandard)) 124 | if(exists==FALSE){ 125 | print("It appears this country is not in the WorldPop set, please check and try again") 126 | break 127 | } 128 | countryreference <- countryreference[,c(1,4,3)] 129 | world_pop_data$CountryStandard <- countryreference[,2] 130 | world_pop_data <- world_pop_data[,c(1,6,2,3,4,5)] 131 | countryreference <- suppressMessages(dcast(countryreference, continent+CountryStandard ~ data_type)) 132 | countryreference <- filter(countryreference, countryreference$CountryStandard==country) 133 | countryreference <- countryreference[,colSums(is.na(countryreference)) res2 143 | pg2 <- content(res2) 144 | 145 | 146 | # extract "form" fields (that page does a POST request) 147 | fields <- html_nodes(pg2, "form#conform > input") 148 | fields <- set_names(xml_attr(fields, "value"), html_attr(fields, "name")) 149 | 150 | ###Submit the form with the field data 151 | POST( 152 | url = "http://www.worldpop.org.uk/data/download/", 153 | add_headers(`Referer` = dataset_link), 154 | body = list( 155 | client_first_name = "", 156 | client_last_name = "", 157 | client_organization = "", 158 | client_country = "", 159 | client_email = "", 160 | client_message = "", 161 | zip_id = fields["zip_id"], 162 | zip_title = fields["zip_title"], 163 | decoy = fields["decoy"], 164 | website = "", 165 | download = "Browse Individual Files" 166 | ), 167 | encode = "form" 168 | ) -> res3 169 | 170 | # find the link that has the file list 171 | pg3 <- content(res3) 172 | html_nodes(pg3, xpath=".//a[contains(., 'switch to')]") %>% 173 | html_attr("href") -> file_list_query_string 174 | 175 | 176 | # follow that link (we need to use some of the previous captured fields) 177 | GET( 178 | url = "http://www.worldpop.org.uk/data/files/index.php", 179 | query = list( 180 | dataset = fields["zip_id"], 181 | action = "dir" 182 | ) 183 | ) -> res4 184 | 185 | ###Get the datasets on the page### 186 | pg4 <- content(res4) 187 | data_frame( 188 | group_name = html_nodes(pg4, "a.dl") %>% html_text(), 189 | href = html_nodes(pg4, "a.dl") %>% html_attr("href") 190 | ) -> downloads 191 | 192 | 193 | 194 | ###Ditch non tif section 195 | downloads$istif <- str_sub(downloads$group_name,-4,-1) 196 | #Some such as senegal are inexplicably .TIF 197 | downloads$istif <- tolower(downloads$istif) 198 | downloads <- filter(downloads, istif==".tif") 199 | 200 | 201 | ###WorldPop decided to have super inconsistent filenames 202 | 203 | pg4charfile <- as.character(downloads[1,"group_name"]) 204 | pg4charfile <- gsub(' {1,}','',pg4charfile) 205 | if(substr(pg4charfile,1,6)!="popmap"){ 206 | if(grepl("\\d", pg4charfile)==TRUE){ 207 | char4 <- substr(pg4charfile,4,4) 208 | char6 <-substr(pg4charfile,6,6) 209 | char9 <-substr(pg4charfile,9,9) 210 | char11 <-substr(pg4charfile,11,11) 211 | char4num <- suppressWarnings(!is.na(as.numeric(char4))) 212 | char6num <- suppressWarnings(!is.na(as.numeric(char6))) 213 | char9num <- suppressWarnings(!is.na(as.numeric(char9))) 214 | char11num <- suppressWarnings(!is.na(as.numeric(char11))) 215 | if(char4num==TRUE & char6num==TRUE){ 216 | downloads$years <-substr(downloads$group_name,4,7) 217 | 218 | } 219 | if(char4num==TRUE & char6num==FALSE){ 220 | downloads$years <-substr(downloads$group_name,4,5) 221 | getfouryear <- function (yearsvec) { 222 | yrFlip = 50 223 | yearsvec <- as.numeric(yearsvec) 224 | yearsvec[yearsvec > yrFlip] <- yearsvec[yearsvec > yrFlip] + 1900 225 | yearsvec[yearsvec < yrFlip] <- yearsvec[yearsvec < yrFlip] + 2000 226 | return(yearsvec) 227 | } 228 | downloads$years <- getfouryear(downloads$years) 229 | } 230 | if(char9num==FALSE & char11num==TRUE){ 231 | downloads$years <-substr(downloads$group_name,11,12) 232 | getfouryear <- function (yearsvec) { 233 | yrFlip = 50 234 | yearsvec <- as.numeric(yearsvec) 235 | yearsvec[yearsvec > yrFlip] <- yearsvec[yearsvec > yrFlip] + 1900 236 | yearsvec[yearsvec < yrFlip] <- yearsvec[yearsvec < yrFlip] + 2000 237 | return(yearsvec) 238 | } 239 | downloads$years <- getfouryear(downloads$years) 240 | } 241 | if(char4num==FALSE & char6num==FALSE & char9num==TRUE){ 242 | downloads$years <- str_extract(downloads$group_name, "\\d{4}") 243 | } 244 | if(char4num==FALSE & char6num==FALSE & char9num==FALSE & char11num==FALSE){ 245 | downloads$years <- str_extract(downloads$group_name, "\\d{4}") 246 | } 247 | }else{downloads$years <- 9999} 248 | }else{ 249 | downloads$years<- as.numeric(substr(downloads$group_name,7,8)) 250 | getfouryear <- function (yearsvec) { 251 | yrFlip = 50 252 | yearsvec <- as.numeric(yearsvec) 253 | yearsvec[yearsvec > yrFlip] <- yearsvec[yearsvec > yrFlip] + 1900 254 | yearsvec[yearsvec < yrFlip] <- yearsvec[yearsvec < yrFlip] + 2000 255 | return(yearsvec) 256 | } 257 | downloads$years <- getfouryear(downloads$years) 258 | } 259 | downloads <- downloads[!is.na(downloads$years),] 260 | 261 | ###Possible Options due to the inexplicable nature of their inconsistent file names 262 | possopt <- c("_pph_", "_ppp_", "_pp_", "uncert", "adj","_M.", "_M_","_F.", "_F_", 263 | "interdecile", "povsd", "125", "200","wpipov", "ppipov", "incpov", 264 | "mpipov", "ANC", "SBA", "PNC", 265 | "A0005", "A0510", "A1015", 266 | "A1520", "A2025", "A2530", 267 | "A3035", "A3540", "A4045", 268 | "A4550", "A5055", "A5560", 269 | "A6065", "A65PL") 270 | opttext <- c("Persons per hectare", "Persons per pixel", "per pixel", " uncertainty dataset showing 95% credible intervals", 271 | "adjusted to match UN estimates", "MALE", "MALE", "FEMALE", "FEMALE", "Uncertainty map", "poverty standard deviation map", "$1.25/day", 272 | "$2.00/day", "mean wealth index", "mean likelihood of living in poverty per grid square", "Income estimate USD per grid square", "%poverty by Multidimensional Poverty Index", 273 | "prob of four or more antenatal care visits at time of delivery", "prob of skilled birth attendance during delivery", "prob of postnatal care received within 48 hours of delivery", 274 | "number of people age 0-5","number of people age 5-10","number of people age 10-15","number of people age 15-20", 275 | "number of people age 20-25","number of people age 25-30","number of people age 30-35", 276 | "number of people age 35-40","number of people age 40-45","number of people age 45-50", 277 | "number of people age 50-55","number of people age 55-60", "number of people age 60-65", 278 | "number of people age 65+") 279 | possoptdf <- data.frame(possopt, opttext, stringsAsFactors = FALSE) 280 | groupsubstr <- str_sub(downloads$group_name,4,-4) 281 | 282 | ###get options for each file from the worldpop selected country and datatype### 283 | optionsforchoice<-foreach(a=1:nrow(downloads), .combine=rbind)%do%{ 284 | theoptions<- foreach(b=1:length(opttext), .combine=cbind)%do%{ 285 | matchoopt <- str_detect(downloads[a,"group_name"],coll(possopt[b])) 286 | if(matchoopt==TRUE){result <-possopt[b]} 287 | if(matchoopt==FALSE){result<- NA} 288 | if(b==13){ 289 | mistake <- str_detect(downloads[a,"group_name"],"\\d{4}") 290 | if(mistake==TRUE){result <- NA} 291 | } 292 | result 293 | } 294 | } 295 | ###get rid of all the nonoptions for selection 296 | optionsforchoice<-do.call(rbind,lapply(1:nrow(optionsforchoice),function(x) t(matrix(optionsforchoice[x,order(is.na(optionsforchoice[x,]))])) )) 297 | optionsforchoice <- as.data.frame(optionsforchoice, stringsAsFactors=FALSE) 298 | optionsforchoice <- optionsforchoice[,colSums(is.na(optionsforchoice))1){ 359 | downpossoptcodes <- data.frame(x=apply(downpossoptcodes,1,function(x) {paste(x[!is.na(x)],collapse='-')})) 360 | } 361 | colnames(downpossoptcodes) <- "optionspossible" 362 | downloads <- as.data.frame(cbind(downloads, downpossoptcodes)) 363 | downloads <- filter(downloads, downloads$years==year) 364 | if(optionschosen!=""){ 365 | downloads2 <- filter(downloads, downloads$optionspossible==optionschosen) 366 | if(is.na(downloads2[1,1]) & length(options)>1){ 367 | optionschosen <- paste0(options[2],"-", options[1], collapse='') 368 | downloads2 <- filter(downloads, downloads$optionspossible==optionschosen) 369 | } 370 | }else{downloads2 <- filter(downloads, is.na(downloads$optionspossible))} 371 | 372 | 373 | 374 | readme_query_stringdownload <- as.character(downloads2[1,"href"]) 375 | 376 | 377 | GET( 378 | url = "http://www.worldpop.org.uk/data/files/index.php", 379 | query = parse_url(readme_query_stringdownload)$query, 380 | progress(), 381 | verbose(), 382 | write_disk(paste0(country,"_", datatype,"_", paste(options, collapse="_"),"_",year, ".tif"), overwrite=TRUE) 383 | )-> res5 384 | } 385 | -------------------------------------------------------------------------------- /R/getWPoptions.R: -------------------------------------------------------------------------------- 1 | #' Get the available options for a country and datatype set from WorldPopUK 2 | #' 3 | #' This function pulls what are the available datasets from WorldPop UK for a 4 | #' given country and datatype. It returns a not available message if the 5 | #' country typed does not exist on WorldPop. To see the available datatypes for 6 | #' a country, see getWPdatatypes() which is intended to be used before this 7 | #' function. 8 | #' 9 | #' Example options returned are "ppp" for persons per pixel, "pph" for persons 10 | #' per hectare, "M" or "F" for male/female tagged sets etc. This function 11 | #' returns all the available options for a given country and datatype. 12 | #' 13 | #' The codes returned in the WP.options dataframe in "OptionCode" columns 14 | #' correspond to the options necessary to include in the getWPdownload() 15 | #' function. 16 | #' 17 | #' If the function returns the year 9999 in the WP.options dataframe, this 18 | #' means the filename on WorldPop is not year tagged. The year will be included 19 | #' if you look up the set manually on WorldPop UK but for the getWPdownload() 20 | #' function you will need to type 9999 for the year as it corresponds to what 21 | #' is given here. 22 | #' 23 | #' As a bonus and to make matching WorldPop sets easier, this function contains 24 | #' correction algorithms to standardize country names to match WorldPop UK sets 25 | #' (i.e. WorldPop has "Côte d'Ivoire", you can type "Ivory Coast" and it will 26 | #' return the WorldPop Côte d'Ivoire set). This function adds a dataframe of 27 | #' the available sets called WP.options to your working environment. 28 | #' 29 | #' 30 | #' @param countryname (character), the name of a country you want to see what 31 | #' data is avaialble from WorldPop for. e.g. \code{“Tanzania”} 32 | #' @param datatype (character), the datatype you would like to see what options 33 | #' are available for WorldPop UK data. e.g. \code{“Population”} 34 | #' @author Neal Thomas Barsch 35 | #' @references WorldPop UK data are attained through the WorldPop UK website. 36 | #' These data are licensensed under the Creative Commons Attribution 4.0 37 | #' License. \url{http://www.worldpop.org.uk/}. 38 | #' 39 | #' Eternal grattitude to StackOverflow member hrbrmstr without whom this 40 | #' function would not have been possible. 41 | #' @examples 42 | #' 43 | #' 44 | #' getWPoptions("Tanzania", "Population") 45 | #' 46 | #' #Example that returns year 9999 47 | #' getWPoptions("Nigeria", "Stunting") 48 | #' 49 | #' @export getWPoptions 50 | getWPoptions <- function (country, datatype) { 51 | ###standardize country name, takes care of stuff like Bolivia (Plurinational State of) or tildes like Côte d'Ivoire 52 | country <- standardizeCountry(paste(country),fuzzyDist=30) 53 | 54 | # Need to "prime" the session with a cookie 55 | res <- GET(url="http://www.worldpop.org.uk/data/data_sources/") 56 | # Get the page contents 57 | pg <- content(res) 58 | # Find the summary links 59 | summary_link_nodes <- html_nodes(pg, xpath=".//a[contains(@href,'summary')]") 60 | map(summary_link_nodes, html_nodes, xpath=".//../..") %>% 61 | map(html_children) %>% 62 | map(html_text) %>% 63 | map(~.[1:4]) %>% 64 | map(as.list) %>% 65 | map_df(set_names, c("continent", "country", "resolution", "data_type")) %>% 66 | bind_cols( 67 | data_frame( 68 | summary_link = sprintf("http://www.worldpop.org.uk%s", html_attr(summary_link_nodes, "href")) 69 | ) 70 | ) -> world_pop_data 71 | world_pop_data$data_type <- gsub("Urban change", "UrbanChange", world_pop_data$data_type) 72 | world_pop_data$data_type <- gsub("Maternal and Newborn Health", "MaternalNewbornHealth", world_pop_data$data_type) 73 | world_pop_data$data_type <- gsub("Contraceptive Use", "ContraceptiveUse", world_pop_data$data_type) 74 | world_pop_data$data_type <- gsub("Age structures", "AgeStructures", world_pop_data$data_type) 75 | world_pop_data$data_type <- gsub("Dynamic Population", "DynamicPopulation", world_pop_data$data_type) 76 | countryreference <- as.data.frame(world_pop_data) 77 | countryreference <- countryreference[,c(1,2,4)] 78 | countryreference <- countryreference[!(countryreference$country)=="N/A",] 79 | world_pop_data <- world_pop_data[!(world_pop_data$country)=="N/A",] 80 | 81 | ###Filter country names so they match the desired country 82 | ###There is probably a better way to do this but I had this code from standardizing country name lists for matching a while back 83 | countryreference$CountryStandard <- standardizeCountry(countryreference[,"country"], fuzzyDist=20) 84 | countryreference$CountryEdit <- gsub("[()]", "", countryreference$country) 85 | countryreference$CountryEdit2 <- gsub("\\s*\\([^\\)]+\\)","",as.character(countryreference$country)) 86 | foreach(a=1:nrow(countryreference)) %do% { 87 | if(countryreference[a,"CountryStandard"]==""){ 88 | countryreference[a,"CountryStandard"] <- standardizeCountry(countryreference[a,"CountryEdit"], fuzzyDist=20) 89 | if(countryreference[a,"CountryStandard"]==""){ 90 | countryreference[a,"CountryStandard"] <- standardizeCountry(countryreference[a,"CountryEdit2"], fuzzyDist=20) 91 | if(countryreference[a,"CountryStandard"]==""){ 92 | countryreference[a,"CountryStandard"] <- toupper(countryreference[a,"country"]) 93 | } 94 | } 95 | } 96 | } 97 | exists <- isTRUE(paste(country) %in% as.character(countryreference$CountryStandard)) 98 | if(exists==FALSE){ 99 | print("It appears this country is not in the WorldPop set, please check and try again") 100 | break 101 | } 102 | countryreference <- countryreference[,c(1,4,3)] 103 | world_pop_data$CountryStandard <- countryreference[,2] 104 | world_pop_data <- world_pop_data[,c(1,6,2,3,4,5)] 105 | countryreference <- suppressMessages(dcast(countryreference, continent+CountryStandard ~ data_type)) 106 | countryreference <- filter(countryreference, countryreference$CountryStandard==country) 107 | countryreference <- countryreference[,colSums(is.na(countryreference)) res2 117 | pg2 <- content(res2) 118 | 119 | 120 | # extract "form" fields (that page does a POST request) 121 | fields <- html_nodes(pg2, "form#conform > input") 122 | fields <- set_names(xml_attr(fields, "value"), html_attr(fields, "name")) 123 | 124 | ###Submit the form with the field data 125 | POST( 126 | url = "http://www.worldpop.org.uk/data/download/", 127 | add_headers(`Referer` = dataset_link), 128 | body = list( 129 | client_first_name = "", 130 | client_last_name = "", 131 | client_organization = "", 132 | client_country = "", 133 | client_email = "", 134 | client_message = "", 135 | zip_id = fields["zip_id"], 136 | zip_title = fields["zip_title"], 137 | decoy = fields["decoy"], 138 | website = "", 139 | download = "Browse Individual Files" 140 | ), 141 | encode = "form" 142 | ) -> res3 143 | 144 | # find the link that has the file list 145 | pg3 <- content(res3) 146 | html_nodes(pg3, xpath=".//a[contains(., 'switch to')]") %>% 147 | html_attr("href") -> file_list_query_string 148 | 149 | 150 | # follow that link (we need to use some of the previous captured fields) 151 | GET( 152 | url = "http://www.worldpop.org.uk/data/files/index.php", 153 | query = list( 154 | dataset = fields["zip_id"], 155 | action = "dir" 156 | ) 157 | ) -> res4 158 | 159 | ###Get the datasets on the page### 160 | pg4 <- content(res4) 161 | data_frame( 162 | group_name = html_nodes(pg4, "a.dl") %>% html_text(), 163 | href = html_nodes(pg4, "a.dl") %>% html_attr("href") 164 | ) -> downloads 165 | 166 | 167 | 168 | ###Ditch non tif section 169 | downloads$istif <- str_sub(downloads$group_name,-4,-1) 170 | #Some such as senegal are inexplicably .TIF 171 | downloads$istif <- tolower(downloads$istif) 172 | downloads <- filter(downloads, istif==".tif") 173 | 174 | 175 | ###WorldPop decided to have super inconsistent filenames 176 | 177 | pg4charfile <- as.character(downloads[1,"group_name"]) 178 | pg4charfile <- gsub(' {1,}','',pg4charfile) 179 | if(substr(pg4charfile,1,6)!="popmap"){ 180 | if(grepl("\\d", pg4charfile)==TRUE){ 181 | char4 <- substr(pg4charfile,4,4) 182 | char6 <-substr(pg4charfile,6,6) 183 | char9 <-substr(pg4charfile,9,9) 184 | char11 <-substr(pg4charfile,11,11) 185 | char4num <- suppressWarnings(!is.na(as.numeric(char4))) 186 | char6num <- suppressWarnings(!is.na(as.numeric(char6))) 187 | char9num <- suppressWarnings(!is.na(as.numeric(char9))) 188 | char11num <- suppressWarnings(!is.na(as.numeric(char11))) 189 | if(char4num==TRUE & char6num==TRUE){ 190 | downloads$years <-substr(downloads$group_name,4,7) 191 | 192 | } 193 | if(char4num==TRUE & char6num==FALSE){ 194 | downloads$years <-substr(downloads$group_name,4,5) 195 | getfouryear <- function (yearsvec) { 196 | yrFlip = 50 197 | yearsvec <- as.numeric(yearsvec) 198 | yearsvec[yearsvec > yrFlip] <- yearsvec[yearsvec > yrFlip] + 1900 199 | yearsvec[yearsvec < yrFlip] <- yearsvec[yearsvec < yrFlip] + 2000 200 | return(yearsvec) 201 | } 202 | downloads$years <- getfouryear(downloads$years) 203 | } 204 | ####PROBLEM this can be true and two sections down can also be true 205 | if(char9num==FALSE & char11num==TRUE){ 206 | downloads$years <-substr(downloads$group_name,11,12) 207 | getfouryear <- function (yearsvec) { 208 | yrFlip = 50 209 | yearsvec <- as.numeric(yearsvec) 210 | yearsvec[yearsvec > yrFlip] <- yearsvec[yearsvec > yrFlip] + 1900 211 | yearsvec[yearsvec < yrFlip] <- yearsvec[yearsvec < yrFlip] + 2000 212 | return(yearsvec) 213 | } 214 | downloads$years <- getfouryear(downloads$years) 215 | } 216 | if(char4num==FALSE & char6num==FALSE & char9num==TRUE){ 217 | downloads$years <- str_extract(downloads$group_name, "\\d{4}") 218 | } 219 | if(char4num==FALSE & char6num==FALSE & char9num==FALSE & char11num==FALSE){ 220 | downloads$years <- str_extract(downloads$group_name, "\\d{4}") 221 | } 222 | }else{downloads$years <- 9999} 223 | }else{ 224 | downloads$years<- as.numeric(substr(downloads$group_name,7,8)) 225 | getfouryear <- function (yearsvec) { 226 | yrFlip = 50 227 | yearsvec <- as.numeric(yearsvec) 228 | yearsvec[yearsvec > yrFlip] <- yearsvec[yearsvec > yrFlip] + 1900 229 | yearsvec[yearsvec < yrFlip] <- yearsvec[yearsvec < yrFlip] + 2000 230 | return(yearsvec) 231 | } 232 | downloads$years <- getfouryear(downloads$years) 233 | } 234 | downloads <- downloads[!is.na(downloads$years),] 235 | 236 | ###Possible Options due to the inexplicable nature of their inconsistent file names 237 | possopt <- c("_pph_", "_ppp_", "_pp_", "uncert", "adj","_M.", "_M_","_F.", "_F_", 238 | "interdecile", "povsd", "125", "200","wpipov", "ppipov", "incpov", 239 | "mpipov", "ANC", "SBA", "PNC", 240 | "A0005", "A0510", "A1015", 241 | "A1520", "A2025", "A2530", 242 | "A3035", "A3540", "A4045", 243 | "A4550", "A5055", "A5560", 244 | "A6065", "A65PL") 245 | opttext <- c("Persons per hectare", "Persons per pixel", "per pixel", " uncertainty dataset showing 95% credible intervals", 246 | "adjusted to match UN estimates", "MALE", "MALE", "FEMALE", "FEMALE", "Uncertainty map", "poverty standard deviation map", "$1.25/day", 247 | "$2.00/day", "mean wealth index", "mean likelihood of living in poverty per grid square", "Income estimate USD per grid square", "%poverty by Multidimensional Poverty Index", 248 | "prob of four or more antenatal care visits at time of delivery", "prob of skilled birth attendance during delivery", "prob of postnatal care received within 48 hours of delivery", 249 | "number of people age 0-5","number of people age 5-10","number of people age 10-15","number of people age 15-20", 250 | "number of people age 20-25","number of people age 25-30","number of people age 30-35", 251 | "number of people age 35-40","number of people age 40-45","number of people age 45-50", 252 | "number of people age 50-55","number of people age 55-60", "number of people age 60-65", 253 | "number of people age 65+") 254 | possoptdf <- data.frame(possopt, opttext, stringsAsFactors = FALSE) 255 | groupsubstr <- str_sub(downloads$group_name,4,-4) 256 | 257 | ###get options for each file from the worldpop selected country and datatype### 258 | optionsforchoice<-foreach(a=1:nrow(downloads), .combine=rbind)%do%{ 259 | theoptions<- foreach(b=1:length(opttext), .combine=cbind)%do%{ 260 | matchoopt <- str_detect(downloads[a,"group_name"],coll(possopt[b])) 261 | if(matchoopt==TRUE){result <-possopt[b]} 262 | if(matchoopt==FALSE){result<- NA} 263 | if(b==13){ 264 | mistake <- str_detect(downloads[a,"group_name"],"\\d{4}") 265 | if(mistake==TRUE){result <- NA} 266 | } 267 | result 268 | } 269 | } 270 | ###get rid of all the nonoptions for selection 271 | optionsforchoice<-do.call(rbind,lapply(1:nrow(optionsforchoice),function(x) t(matrix(optionsforchoice[x,order(is.na(optionsforchoice[x,]))])) )) 272 | optionsforchoice <- as.data.frame(optionsforchoice, stringsAsFactors=FALSE) 273 | optionsforchoice <- optionsforchoice[,colSums(is.na(optionsforchoice)) gadmresp, 146 | error=function(e){noGADM <- TRUE}) 147 | if(!isTRUE(gadmresp)){gadmresp <- FALSE} 148 | if(!isTRUE(noGADM) & !isTRUE(gadmresp)){unzip(paste0("gadm",i,".zip"), exdir=paste0("gadm",i), overwrite=TRUE)} 149 | } 150 | 151 | ###Get the lowest GADM layer to overlay. Lowest layers come with higher division codes as well 152 | dGADM <- file.exists(paste0("gadm",i)) 153 | if(isTRUE(dGADM)){ 154 | writeLines(c("",paste0("SHAPEFILE SUCCESS!: ", uni.loc[a,"CountryName"] ))) 155 | 156 | if(is.character(gadmlevel)){ 157 | listfiles <-list.files(paste0("gadm",i,"/")) 158 | 159 | ###Sometimes license.txt gets in the wrong place 160 | listfiles <- gsub("license.txt","aaa.txt", listfiles) 161 | listfiles <- sort(listfiles) 162 | smallest.file <- substr(listfiles[length(listfiles)],8,8) 163 | gadmlevel <- as.numeric(smallest.file) 164 | } 165 | 166 | ###Shapefile read (using sf) 167 | sptemp <- sf::st_read(dsn=paste0("gadm",i), layer=paste0(i,"_adm",gadmlevel), quiet=TRUE) 168 | 169 | flist <- list() 170 | glist <- list() 171 | 172 | 173 | ###Over SF methods for determining dataset locations administrative levels 174 | sp.locations <- locations.df[ which(locations.df$iso3c==i ), ] 175 | sf.locations <- st_as_sf(sp.locations, coords=c("lon","lat"), crs= 4326) 176 | over <- suppressWarnings(suppressMessages(st_intersection(sf.locations,sptemp))) 177 | st_geometry(over) <- NULL 178 | over <- suppressMessages(left_join(over, sptemp[,c(paste0("ID_",gadmlevel), "geometry")])) 179 | sp.locations <- as.data.frame(sp.locations) 180 | df.loc <- bind_cols(sp.locations[,c("lat", "lon")], over) 181 | 182 | 183 | ### Took out df.loc<- suppressMessages(suppressWarnings(left_join(sp.locations, over))) 184 | 185 | df.loc[grep('^ID_', names(df.loc))] <- lapply(df.loc[grep('^ID_', names(df.loc))], as.character) 186 | df.loc[grep('iso3c', names(df.loc))] <- lapply(df.loc[grep('iso3c', names(df.loc))], as.character) 187 | ##get area and modify format 188 | df.loc$area_a <- st_area(df.loc$geometry) 189 | df.loc$area_a <- as.numeric(df.loc$area_a) 190 | df.loc$area_a_sqkm <- df.loc[,"area_a"]/1000000 191 | df.loc[grep('^ID_', names(df.loc))] <- lapply(df.loc[grep('^ID_', names(df.loc))], as.character) 192 | 193 | justid <- df.loc[ , grepl( "ID_" , colnames( df.loc ) ) ] 194 | 195 | flist[[1]] <- cbind(justid, df.loc[,c("area_a", "area_a_sqkm", "geometry")]) 196 | glist[[1]] <- cbind(justid, df.loc[,c("countryplace", "lat", "lon", 197 | "CountryName", "iso3c", "area_a", "area_a_sqkm")]) 198 | 199 | colnames(flist[[1]])[colnames(flist[[1]])=='geometry'] <- paste0("geometry",gadmlevel) 200 | colnames(flist[[1]])[colnames(flist[[1]])=='area_a'] <- paste0("area_",gadmlevel,"_Msq") 201 | colnames(flist[[1]])[colnames(flist[[1]])=='area_a_sqkm'] <- paste0("area_",gadmlevel,"_KMsq") 202 | 203 | colnames(glist[[1]])[colnames(glist[[1]])=='geometry'] <- paste0("geometry",gadmlevel) 204 | colnames(glist[[1]])[colnames(glist[[1]])=='area_a'] <- paste0("area_",gadmlevel,"_Msq") 205 | colnames(glist[[1]])[colnames(glist[[1]])=='area_a_sqkm'] <- paste0("area_",gadmlevel,"_KMsq") 206 | 207 | if(isTRUE(fill)){ 208 | rgadmlevel <- gadmlevel 209 | rr <-2 210 | repeat{ 211 | rgadmlevel <- rgadmlevel - 1 212 | if(rgadmlevel<0){break} 213 | sptemp <- suppressWarnings(sf::st_read(dsn=paste0("gadm",i), layer=paste0(i,"_adm",rgadmlevel), quiet=TRUE)) 214 | over <- suppressWarnings(suppressMessages(st_intersection(sf.locations,sptemp))) 215 | over <- over[,c(paste0("ID_",rgadmlevel))] 216 | st_geometry(over) <- NULL 217 | over <- unique(over) 218 | over <- suppressMessages(left_join(over, sptemp[,c(paste0("ID_",rgadmlevel), "geometry")])) 219 | over[grep('^ID_', names(over))] <- lapply(over[grep('^ID_', names(over))], as.character) 220 | over$area_a <- st_area(over$geometry) 221 | over$area_a <- as.numeric(over$area_a) 222 | over$area_a_sqkm <- over[,"area_a"]/1000000 223 | ### dont think need this: over <- suppressMessages(left_join(over, df.loc[,c(paste0("ID_",rgadmlevel),"countryplace")])) 224 | colnames(over)[colnames(over)=='geometry'] <- paste0("geometry",rgadmlevel) 225 | colnames(over)[colnames(over)=='area_a'] <- paste0("area_",rgadmlevel,"_Msq") 226 | colnames(over)[colnames(over)=='area_a_sqkm'] <- paste0("area_",rgadmlevel,"_KMsq") 227 | gover <- over[,c(1, 3, 4)] 228 | flist[[rr]]<- over 229 | glist[[rr]]<- gover 230 | rr <- rr+1 231 | } 232 | } 233 | } 234 | globalgeo[[a]] <- flist 235 | globalstat[[a]] <- glist 236 | a <- a+1 237 | ###Delete GADM shapefile in disk space (wd) if default deleteGADM=TRUE. Used for all extraction already 238 | if(isTRUE(deleteGADM) & isTRUE(dGADM)){ 239 | file.remove(paste0("gadm",i,".zip")) 240 | unlink(paste0("gadm",i, "/*")) 241 | file.remove(paste0("gadm",i,"/")) 242 | } 243 | } 244 | MASTERstat <- list() 245 | foreach(p=1:length(globalstat))%do%{ 246 | MASTERstat[[p]] <- suppressMessages(Reduce(left_join, globalstat[[p]])) 247 | } 248 | MASTERstat <- suppressWarnings(do.call("bind_rows",MASTERstat)) 249 | 250 | ###MASTERgeo <<- globalgeo 251 | foreach(g=1:length(globalgeo))%do%{ 252 | n.lgg <- length(globalgeo[[g]]) 253 | globalgeo[[g]][[n.lgg]] <- suppressMessages(inner_join(globalgeo[[g]][[n.lgg]], 254 | as.data.frame(unique(MASTERstat[,c("ID_0", "CountryName")])))) 255 | checkin1 <<- TRUE 256 | } 257 | MASTERgeo <<- globalgeo 258 | colnames(MASTERstat) <- paste("sp", colnames(MASTERstat), sep="_") 259 | colnames(MASTERstat)[colnames(MASTERstat)=="sp_lat"] <- "lat" 260 | colnames(MASTERstat)[colnames(MASTERstat)=="sp_lon"] <- "lon" 261 | MASTERstat <<- MASTERstat 262 | MASTERout <<- suppressMessages(left_join(dfname, MASTERstat)) 263 | writeLines(c("",green("Written to Global Environment:"), 264 | "MASTERgeo is your list of geometries. Use it for extraction functions.", 265 | "MASTERout is your dataset bound with newly attached geocoding.", 266 | "MASTERstat is your dataset of unique locations in the dataset, unbound.")) 267 | 268 | 269 | } 270 | 271 | 272 | 273 | 274 | 275 | 276 | 277 | 278 | 279 | 280 | 281 | -------------------------------------------------------------------------------- /R/spheatGPS_dep.R: -------------------------------------------------------------------------------- 1 | #' DEPRECIATED: NEW FUNCTION IS spheatGPS() 2 | #' Reverse geocode GPS coordinates in a dataset 3 | #' 4 | #' Reverse geocode latitude and longitude columns in a dataset with 5 | #' administrative layers determined by GADM layers 6 | #' 7 | #' 8 | #' @param dataset (character), the name of the data frame containing a column 9 | #' of place names. e.g. \code{“mydataframe”} 10 | #' @param latcol (character), the name of the column in the data frame 11 | #' containing LATITUDES \code{“mylatcol”} 12 | #' @param loncol (character), the name of the column in the data frame 13 | #' containing LONGITUDES \code{“myloncol”} 14 | #' @param googleapikey (character), a valid Google Maps API key. See 15 | #' https://developers.google.com/maps/documentation/javascript/get-api-key to 16 | #' attain one. 17 | #' @param oride (logical), if you already have the specified shapefile 18 | #' downloads from GADM for each country in your data frame, you may override 19 | #' the GADM downloads included in a-heat using oride=TRUE. ONLY do this if you 20 | #' are sure you have the GADM shapefiles for every country in your set already 21 | #' in your R working directory. Default is oride=FALSE 22 | #' @param deleteGADM (logical), if after geocoding you would like to keep the 23 | #' GADM shapefiles downloaded in your working directory you may use 24 | #' deleteGADM=FALSE. The files can be large, especially if you have many 25 | #' countries in your dataset. Use carefully, could cause many large GADM 26 | #' shapefiles saved to your working directory. The default is deleteGADM=TRUE. 27 | #' @author Neal Thomas Barsch 28 | #' @references GADM DATA are attained through the GADM project website. 29 | #' Commercial use of this function is not allowed without prior permission from 30 | #' GADM.org. \url{http://gadm.org/}. 31 | #' @examples 32 | #' 33 | #' 34 | #' spheatGPS_dep("myDataframe", "myLatColumnName","myLonColumnName", "mygoogleapikey") 35 | #' 36 | #' #Keeping all GADM shapefiles 37 | #' spheatGPS_dep("myDataframe", "myLatColumnName","myLonColumnName", "mygoogleapikey", deleteGADM=FALSE) 38 | #' 39 | #' #You already have the GADM shapefiles and don't want to redownload or delete them 40 | #' spheatGPS_dep("myDataframe", "myLatColumnName","myLonColumnName", "mygoogleapikey", oride=TRUE, deleteGADM=FALSE) 41 | #' 42 | #' 43 | #' @export spheatGPS_dep 44 | spheatGPS_dep <- function (dataset, latcol,loncol, googleapikey, oride=FALSE, deleteGADM=TRUE) { 45 | dfname <- get(dataset) 46 | dfname[,latcol] <- as.numeric(as.character(dfname[,latcol])) 47 | dfname[,loncol] <- as.numeric(as.character(dfname[,loncol])) 48 | dfname$latlonccc <- paste0(dfname[,latcol],"-",dfname[,loncol]) 49 | uni.loc<- subset(dfname, !duplicated(latlonccc)) 50 | uni.loc <- subset(uni.loc, latlonccc!="NA-NA") 51 | uni.loc <- uni.loc[!(is.na(uni.loc[,"latlonccc"]) | uni.loc[,"latlonccc"]=="-"),] 52 | iters.look <- nrow(uni.loc) 53 | pb = txtProgressBar(min = 0, max = iters.look, initial = 0, style=3) 54 | print(paste("...Reverse geocoding your locations in dataset, please wait...")) 55 | locations.df <- foreach(a=1:iters.look, .combine=rbind) %do% { 56 | setTxtProgressBar(pb,a) 57 | gway.df <- google_reverse_geocode(location=c(as.numeric(uni.loc[a,latcol]), 58 | as.numeric(uni.loc[a,loncol])), 59 | simplify=TRUE, 60 | key=googleapikey) 61 | gway.df<- as.data.frame(gway.df) 62 | gway.df <- gway.df[1,"results.formatted_address"] 63 | gway.df <- as.data.frame(gway.df) 64 | gway.df$lat <- uni.loc[a,latcol] 65 | gway.df$lon <- uni.loc[a,loncol] 66 | gway.df$PlacenameGeocoded <- gway.df[,"gway.df"] 67 | gway.df <- gway.df[,2:ncol(gway.df)] 68 | gway.df 69 | } 70 | dfname<- dfname[ , -which(names(dfname) %in% c("latlonccc"))] 71 | locations.df$lat <- as.numeric(as.character(locations.df[,"lat"])) 72 | locations.df$lon <- as.numeric(as.character(locations.df[,"lon"])) 73 | locations.df$PN <- gsub('[0-9]','', as.character(locations.df[,"PlacenameGeocoded"])) 74 | locations.df$PN <- gsub(' ,',',', as.character(locations.df[,"PN"])) 75 | locations.df$country <- sub(".*,\\s*([^,]+)$", "\\1", locations.df$PN) 76 | locations.df$iso3c <- countrycode(locations.df[,"country"], 'country.name', 'iso3c') 77 | uni.loc<- subset(locations.df, !duplicated(iso3c)) 78 | uni.loc<- subset(uni.loc, !is.na(iso3c)) 79 | a <-1 80 | clist <- list() 81 | pb = txtProgressBar(min = 0, max = nrow(uni.loc), initial = 0, style=3) 82 | for(i in uni.loc[,"iso3c"]){ 83 | if(oride!=TRUE){ 84 | curl_download(paste0("http://biogeo.ucdavis.edu/data/gadm2.8/shp/", i,"_adm_shp.zip"), 85 | destfile=paste0("gadm",i,".zip")) 86 | unzip(paste0("gadm",i,".zip"), exdir=paste0("gadm",i), overwrite=TRUE) 87 | } 88 | listfiles <-list.files(paste0("gadm",i,"/")) 89 | listfiles <- gsub("license.txt","aaa.txt", listfiles) 90 | listfiles <- sort(listfiles) 91 | smallest.file <- substr(listfiles[length(listfiles)],8,8) 92 | sptemp <- readOGR(dsn=paste0("gadm",i), layer=paste0(i,"_adm",smallest.file)) 93 | sp.locations <- locations.df[ which(locations.df$iso3c==i ), ] 94 | coordinates(sp.locations) <- ~lon+lat 95 | proj4string(sp.locations)=CRS("+proj=longlat +datum=WGS84 +no_defs +ellps=WGS84 +towgs84=0,0,0") 96 | over <- over(sp.locations,sptemp) 97 | sp.locations <- as.data.frame(sp.locations) 98 | clist[[a]] <- data.frame(sp.locations, over) 99 | clist[[a]] <- lapply(clist[[a]], as.character) 100 | setTxtProgressBar(pb,a) 101 | a <- a+1 102 | if(exists("deleteGADM")){ 103 | if(deleteGADM==TRUE){ 104 | file.remove(paste0("gadm",i,".zip")) 105 | unlink(paste0("gadm",i, "/*")) 106 | file.remove(paste0("gadm",i,"/")) 107 | } 108 | } 109 | } 110 | masterloc <- do.call("bind_rows",clist) 111 | masterloc <- as.data.frame(masterloc) 112 | masterloc$lat <- as.numeric(masterloc[,"lat"]) 113 | masterloc$lon <- as.numeric(masterloc[,"lon"]) 114 | names(masterloc)[names(masterloc) == "lat"] <- paste(latcol) 115 | names(masterloc)[names(masterloc) == "lon"] <- paste(loncol) 116 | masterloc <- masterloc[, colSums(is.na(masterloc)) != nrow(masterloc)] 117 | dfname <- suppressMessages(left_join(dfname, masterloc)) 118 | MASTER_gps <<- dfname 119 | } 120 | -------------------------------------------------------------------------------- /R/spheatLookup.R: -------------------------------------------------------------------------------- 1 | #' Geocode a list of places manually typed into the function in a loop 2 | #' 3 | #' Geocode a list of places manually typed into spaceheater in a loop with 4 | #' administrative layers determined by GADM layers. The function will prompt 5 | #' the user to type place names until the user is finished (indicated by typing 6 | #' DONE). The function returns a dataframe of all typed locations with GADM 7 | #' administrative levels and GPS coordinates. This function is only useful if 8 | #' your locations are not already in a data frame, see spheatNames() if you 9 | #' already have locations in data frame format. 10 | #' 11 | #' 12 | #' @param googleapikey (character), a valid Google Maps API key. See 13 | #' https://developers.google.com/maps/documentation/javascript/get-api-key to 14 | #' attain one. 15 | #' @param oride (logical), if you already have the specified shapefile 16 | #' downloads from GADM for each country in your data frame, you may override 17 | #' the GADM downloads included in a-heat using oride=TRUE. ONLY do this if you 18 | #' are sure you have the GADM shapefiles for every country in your set already 19 | #' in your R working directory. Default is oride=FALSE 20 | #' @param deleteGADM (logical), if after geocoding you would like to keep the 21 | #' GADM shapefiles downloaded in your working directory you may use 22 | #' deleteGADM=FALSE. The files can be large, especially if you have many 23 | #' countries in your dataset. Use carefully, could cause many large GADM 24 | #' shapefiles saved to your working directory. The default is deleteGADM=TRUE. 25 | #' @author Neal Thomas Barsch 26 | #' @references GADM DATA are attained through the GADM project website. 27 | #' Commercial use of this function is not allowed without prior permission from 28 | #' GADM.org. \url{http://gadm.org/}. 29 | #' @examples 30 | #' 31 | #' 32 | #' spheatLookup("mygoogleapikey") 33 | #' 34 | #' #Keeping all GADM shapefiles 35 | #' spheatLookup("mygoogleapikey", deleteGADM=FALSE) 36 | #' 37 | #' #You already have the GADM shapefiles and don't want to redownload or delete them 38 | #' spheatLookup("mygoogleapikey", oride=TRUE, deleteGADM=FALSE) 39 | #' 40 | #' 41 | #' @export spheatLookup 42 | spheatLookup <- function (googleapikey, oride=FALSE, deleteGADM=TRUE) { 43 | replacebug <-"n" 44 | a <- 1 45 | locations.df <- NULL 46 | repeat{ 47 | uinput.location <- readline(prompt="Enter Location or DONE (Country, State, Address, or other Place Name): ") 48 | if(uinput.location=="DONE"){break} 49 | uinput.newname <- gsub(' ','',uinput.location) 50 | if(uinput.newname=="NewYork,NewYork"){ 51 | replacebug <- uinput.newname 52 | uinput.newname <- gsub('NewYork,NewYork','Empire State Building',uinput.newname) 53 | } 54 | gway.df <- google_geocode(uinput.newname,key=googleapikey) 55 | if(gway.df$status=="ZERO_RESULTS"){ 56 | print(paste0("...Could not find entry: ", uinput.location)) 57 | uinput.newname <- readline(prompt="Replace with manual entry: ") 58 | uinput.newname <- gsub(' ','',uinput.newname) 59 | gway.df <- google_geocode(paste(uinput.newname),key=googleapikey) 60 | } 61 | gway.df<- unlist(gway.df) 62 | gway.df<- as.data.frame(gway.df) 63 | gway.df <- as.data.frame(gway.df[c("results.geometry.location.lat","results.geometry.location.lng","results.formatted_address"), "gway.df"]) 64 | colnames(gway.df)<-"gway" 65 | gway.df <- t(gway.df) 66 | gway.df <- data.frame(r1= row.names(gway.df), gway.df, row.names=NULL) 67 | if(replacebug=="NewYork,NewYork"){ 68 | uinput.location<-replacebug 69 | } 70 | gway.df$namelook <- uinput.location 71 | gway.df <- gway.df[,2:ncol(gway.df)] 72 | colnames(gway.df) <- c("lat", "lon","PlacenameGeocoded", "namelook") 73 | replacebug <-"n" 74 | locations.df <- rbind(locations.df, gway.df) 75 | } 76 | locations.df$lat <- as.numeric(as.character(locations.df[,"lat"])) 77 | locations.df$lon <- as.numeric(as.character(locations.df[,"lon"])) 78 | locations.df$PN <- gsub('[0-9]','', as.character(locations.df[,"PlacenameGeocoded"])) 79 | locations.df$PN <- gsub(' ,',',', as.character(locations.df[,"PN"])) 80 | locations.df$country <- sub(".*,\\s*([^,]+)$", "\\1", locations.df$PN) 81 | locations.df$iso3c <- countrycode(locations.df[,"country"], 'country.name', 'iso3c') 82 | uni.loc<- subset(locations.df, !duplicated(iso3c)) 83 | uni.loc<- subset(uni.loc, !is.na(iso3c)) 84 | a <-1 85 | clist <- list() 86 | pb = txtProgressBar(min = 0, max = nrow(uni.loc), initial = 0, style=3) 87 | for(i in uni.loc[,"iso3c"]){ 88 | if(oride!=TRUE){ 89 | curl_download(paste0("http://biogeo.ucdavis.edu/data/gadm2.8/shp/", i,"_adm_shp.zip"), 90 | destfile=paste0("gadm",i,".zip")) 91 | unzip(paste0("gadm",i,".zip"), exdir=paste0("gadm",i), overwrite=TRUE) 92 | } 93 | listfiles <-list.files(paste0("gadm",i,"/")) 94 | listfiles <- gsub("license.txt","aaa.txt", listfiles) 95 | listfiles <- sort(listfiles) 96 | smallest.file <- substr(listfiles[length(listfiles)],8,8) 97 | sptemp <- readOGR(dsn=paste0("gadm",i), layer=paste0(i,"_adm",smallest.file)) 98 | sp.locations <- locations.df[ which(locations.df$iso3c==i ), ] 99 | coordinates(sp.locations) <- ~lon+lat 100 | proj4string(sp.locations)=CRS("+proj=longlat +datum=WGS84 +no_defs +ellps=WGS84 +towgs84=0,0,0") 101 | over <- over(sp.locations,sptemp) 102 | sp.locations <- as.data.frame(sp.locations) 103 | clist[[a]] <- data.frame(sp.locations, over) 104 | setTxtProgressBar(pb,a) 105 | a <- a+1 106 | if(deleteGADM!=FALSE){ 107 | file.remove(paste0("gadm",i,".zip")) 108 | unlink(paste0("gadm",i, "/*")) 109 | file.remove(paste0("gadm",i,"/")) 110 | } 111 | } 112 | 113 | masterloc <- do.call("bind_rows",clist) 114 | masterloc <- as.data.frame(masterloc) 115 | masterloc$lat <- as.numeric(masterloc[,"lat"]) 116 | masterloc$lon <- as.numeric(masterloc[,"lon"]) 117 | masterloc$latlong <- paste0(masterloc[,"lat"],"-",masterloc[,"lon"]) 118 | masterloc <- masterloc[, colSums(is.na(masterloc)) != nrow(masterloc)] 119 | MASTER_lookup <<- masterloc 120 | } 121 | 122 | -------------------------------------------------------------------------------- /R/spheatNames.R: -------------------------------------------------------------------------------- 1 | #' Geocode place names in a dataset 2 | #' 3 | #' geocode a vector of names in a dataset with administrative layers determined 4 | #' by GADM layers 5 | #' 6 | #' 7 | #' @param dataset (character), the name of the data frame containing a column 8 | #' of place names. e.g. \code{“mydataframe”} 9 | #' @param colname (character), the name of the column in the data frame 10 | #' containing place names e.g. \code{“mycolname”} 11 | #' @param googleapikey (character), a valid Google Maps API key. See 12 | #' https://developers.google.com/maps/documentation/javascript/get-api-key to 13 | #' attain one. 14 | #' @param oride (logical), if you already have the specified shapefile 15 | #' downloads from GADM for each country in your data frame, you may override 16 | #' the GADM downloads included in a-heat using oride=TRUE. ONLY do this if you 17 | #' are sure you have the GADM shapefiles for every country in your set already 18 | #' in your R working directory. Default is oride=FALSE 19 | #' @param deleteGADM (logical), if after geocoding you would like to keep the 20 | #' GADM shapefiles downloaded in your working directory you may use 21 | #' deleteGADM=FALSE. The files can be large, especially if you have many 22 | #' countries in your dataset. Use carefully, could cause many large GADM 23 | #' shapefiles saved to your working directory. The default is deleteGADM=TRUE. 24 | #' 25 | #' 26 | #' 27 | #' @author Neal Thomas Barsch 28 | #' @references GADM DATA are attained through the GADM project website. 29 | #' Commercial use of this function is not allowed without prior permission from 30 | #' GADM.org. \url{http://gadm.org/}. 31 | #' @examples 32 | #' 33 | #' 34 | #' spheatNAMES("myDataframe", "myColWithPlaceNames", "mygoogleapikey") 35 | #' 36 | #' #Keeping all GADM shapefiles 37 | #' spheatNAMES("myDataframe", "myColWithPlaceNames", "mygoogleapikey", deleteGADM=FALSE) 38 | #' 39 | #' #You already have the GADM shapefiles and don't want to redownload or delete them 40 | #' spheatNAMES("myDataframe", "myColWithPlaceNames", "mygoogleapikey", oride=TRUE, deleteGADM=FALSE) 41 | #' 42 | #' 43 | #' @export spheatNAMES 44 | spheatNAMES <- function (dataset, colname, googleapikey, gadmlevel="lowest", fill=TRUE, skipMissing=FALSE, orideGADM=FALSE, deleteGADM=TRUE) { 45 | 46 | ###Get dataset to merge on and column to look up 47 | ### Replaced dfname <- get(dataset) 48 | replacebug <-"n" 49 | dfname <- dataset 50 | 51 | dfname[,sapply(dfname,is.character)] <- sapply( 52 | dfname[,sapply(dfname,is.character)], 53 | iconv,"WINDOWS-1252","UTF-8") 54 | 55 | 56 | 57 | dfname[grep('ID_', names(dfname))] <- lapply(dfname[grep('ID_', names(dfname))], as.character) 58 | dfname$namelookorig <- dfname[,paste0(colname)] 59 | dfname$namelook <- tolower(dfname$namelookorig) 60 | dfname$namelook <- gsub("^ *|(?<= ) | *$", "", dfname$namelook, perl = TRUE) 61 | dfname$namelook <- gsub(", ", ",", dfname$namelook) 62 | 63 | ###Minor housekeeping with the names before fed to google 64 | lookcol <- dfname[,"namelook"] 65 | lookcol <- as.data.frame(lookcol) 66 | colnames(lookcol) <- "lookcol" 67 | lookcol$lookcol <- as.character(lookcol[,"lookcol"]) 68 | lookcol <- lookcol[!(is.na(lookcol[,"lookcol"]) | lookcol[,"lookcol"]==""),] 69 | 70 | 71 | ###Housekeeping 72 | if(is.character(gadmlevel)){ 73 | gadmlevel <- tolower(gadmlevel) 74 | if(gadmlevel=="village"){gadmlevel <-"lowest" } 75 | if(gadmlevel=="state"){gadmlevel <-1 } 76 | if(gadmlevel=="province"){gadmlevel <-1 } 77 | if(gadmlevel=="low"){gadmlevel <-"lowest" } 78 | if(gadmlevel=="l"){gadmlevel <-"lowest" } 79 | if(gadmlevel=="h"){gadmlevel <-0 } 80 | if(gadmlevel=="high"){gadmlevel <-0 } 81 | if(gadmlevel=="country"){gadmlevel <-0 } 82 | if(gadmlevel=="highest"){gadmlevel <- 0} 83 | if(gadmlevel=="lowestcommon"){gadmlevel <- "lcl"} 84 | if(gadmlevel=="lowest common"){gadmlevel <- "lcl"} 85 | if(gadmlevel=="lc"){gadmlevel <- "lcl"} 86 | if(gadmlevel=="common"){gadmlevel <- "lcl"} 87 | 88 | 89 | 90 | if(gadmlevel=="lcl" | gadmlevel=="lowest") { 91 | load("gadm_levels28.RData") 92 | gadm_levels2 <- gadm_levels2[,c("iso3c", "level")] 93 | ### deleted gadm_levels2[grep('iso3c', names(gadm_levels2))] <- lapply(gadm_levels2[grep('iso3c', names(gadm_levels2))], as.character) 94 | } 95 | } 96 | 97 | 98 | 99 | 100 | ###Taking only unique text lookups and merging later will speed sets with dup locations 101 | lookVector <- unique(lookcol) 102 | iters.look <- length(lookVector) 103 | 104 | #Replace progress bar 105 | 106 | print(paste("...Geocoding your locations in dataset, please wait...")) 107 | pb = txtProgressBar(min = 0, max = 100, initial = 0, style=3) 108 | ###Making defaults of deleting all and skipping all FALSE 109 | skipall <- FALSE 110 | 111 | if ("skipall" %in% ls(envir = .GlobalEnv) && missing(skipall)) { 112 | skipall<- get("skipall", envir = .GlobalEnv) 113 | } 114 | if(isTRUE(skipMissing)){skipall <- TRUE} 115 | 116 | 117 | 118 | ###Looking up and geocoding locations (below) 119 | 120 | testlist <- list() 121 | ### DELETED .combine=rbind put it back 122 | locations.df <- foreach(a=1:iters.look, .combine=rbind) %do% { 123 | replacebug <- "n" 124 | ###There is an odd bug where if you look up New York, New York, it thinks you mean the hotel in Las Vegas 125 | ###Below fixes that small bug (by switching the lookup location to Empire State Building) 126 | if(lookVector[a]=="new york,new york"){ 127 | replacebug <- lookVector[a] 128 | lookVector[a] <- "empire state building" 129 | } 130 | gwayerror <- FALSE 131 | 132 | ###geocode text locations w googleway 133 | gway.df <- tryCatch(google_geocode(paste0("\"",lookVector[a],"\""),key=googleapikey), 134 | error=function(e){gwayerror <- TRUE}) 135 | 136 | ###Give user a chance to type a manual entry not found, or delete or ignore the entry 137 | if(gway.df$status=="ZERO_RESULTS" | isTRUE(gwayerror)){ 138 | if(gway.df$status=="ZERO_RESULTS") {nores <- "no google maps result"} 139 | if(isTRUE(gwayerror)) {nores <- "internet error, or invalid symbol error"} 140 | 141 | j <- 1 142 | repeat{ 143 | ###Set default repeat continue to TRUE 144 | dcont <- TRUE 145 | ###repeats don't have to go through again after choosing one of the 'all' options 146 | if(!(isTRUE(skipall))){ 147 | writeLines(c( "", 148 | "", 149 | paste0("Could not find entry: ", red(lookVector[a])), 150 | paste0("Due to ", red(paste0(nores) )), 151 | "", 152 | underline(blue("OPTIONS:")), 153 | paste0("RETRY: " ,blue("Hit enter")), 154 | paste0("TYPE CORRECTED PLACE NAME: ", blue("Type the corrected place name for: "),red(lookVector[a])), 155 | paste0("SKIP ENTRY: ", blue("Type 's or skip'")), 156 | paste0("SKIP ALL NOT FOUND ENTRIES: ", blue("Type 'sa or skip all'")) 157 | ) 158 | ) 159 | 160 | uinput.newname <- readline(prompt="TYPE AN OPTION GIVEN ABOVE: ") 161 | 162 | ###Some housekeeping 163 | uinput.newname <- gsub("^ *|(?<= ) | *$", "", uinput.newname, perl = TRUE) 164 | uinput.newname <- tolower(uinput.newname) 165 | if(uinput.newname=="s"){uinput.newname <- "skip"} 166 | if(uinput.newname=="sa"){uinput.newname <- "skip all"} 167 | if(uinput.newname=="skip a"){uinput.newname <- "skip all"} 168 | if(uinput.newname=="s all"){uinput.newname <- "skip all"} 169 | if(uinput.newname=="s a"){uinput.newname <- "skip all"} 170 | if(uinput.newname=="sa"){uinput.newname <- "skip all"} 171 | if(uinput.newname=="all"){uinput.newname <- "skip all"} 172 | } 173 | 174 | ###axeem and skipall back in play 175 | if(isTRUE(skipall)){uinput.newname <- "skip all"} 176 | 177 | ###all processes that SKIP 178 | if(uinput.newname=="skip" | uinput.newname=="skip all"){ 179 | dfname <- as.data.frame(dfname) 180 | coltemp <- (which(dfname$namelook==lookVector[a])) 181 | dfname[c(paste(coltemp), collapse=","),"namelook"] <- "SKIP" 182 | lookVector[a] <- "SKIP" 183 | if(uinput.newname=="skip all"){skipall <- TRUE} 184 | break 185 | } 186 | 187 | 188 | ###Set dcont to continue for another google geocode 189 | dcont <- TRUE 190 | gwayerror <- FALSE 191 | if(isTRUE(dcont)){ 192 | gway.df <- tryCatch(google_geocode(paste(uinput.newname),key=googleapikey), 193 | error=function(e){gwayerror <- TRUE}) 194 | 195 | } 196 | ###If new match successful 197 | if(!(gway.df$status=="ZERO_RESULTS") & !isTRUE(gwayerror)){ 198 | n.gwaydf <- nrow(gway.df$results) 199 | if(n.gwaydf!=1){ 200 | resy <- as.data.frame(gway.df$results) 201 | clost <- stringdist::amatch(paste0(lookVector[a]),resy[,"formatted_address"], maxDist=500) 202 | gway.df$results <- gway.df$results[clost,] 203 | } 204 | dfname <- as.data.frame(dfname) 205 | coltemp <- (which(dfname$namelook==lookVector[a])) 206 | dfname[c(paste(coltemp), collapse=","),"namelook"] <- uinput.newname 207 | lookVector[a] <- uinput.newname 208 | break 209 | } 210 | j <- j+1 211 | } 212 | }else{ 213 | n.gwaydf <- nrow(gway.df$results) 214 | if(n.gwaydf!=1){ 215 | resy <- as.data.frame(gway.df$results) 216 | clost <- stringdist::amatch(paste0(lookVector[a]),resy[,"formatted_address"], maxDist=500) 217 | gway.df$results <- gway.df$results[clost,] 218 | } 219 | } 220 | ###If not skip this entry 221 | if(!(is.na(lookVector[a]))){ 222 | gway.df<- unlist(gway.df) 223 | gway.df<- as.data.frame(gway.df) 224 | gway.df <- as.data.frame(gway.df[c("results.geometry.location.lat", 225 | "results.geometry.location.lng", 226 | "results.formatted_address"), "gway.df"]) 227 | colnames(gway.df)<-"gway" 228 | gway.df <- t(gway.df) 229 | gway.df <- data.frame(r1= row.names(gway.df), gway.df, row.names=NULL) 230 | ###Weird new york bug see above, putting original back 231 | if(replacebug=="new york,new york"){ 232 | lookVector[a]<-replacebug 233 | } 234 | gway.df$namelook <- lookVector[a] 235 | gway.df <- gway.df[,2:ncol(gway.df)] 236 | colnames(gway.df) <- c("lat", "lon","PlacenameGeocoded", "namelook") 237 | replacebug <-"n" 238 | } 239 | ####good to here on a47 240 | ###If skip this entry enter NA for merge 241 | if(is.na(lookVector[a])){ 242 | gway.df <- data.frame( 243 | lat=as.factor(NA), 244 | lon=as.factor(NA), 245 | PlacenameGeocoded=as.factor(NA), 246 | namelook=as.character("SKIP") 247 | ) 248 | } 249 | setTxtProgressBar(pb, (a/iters.look)*100) 250 | return(gway.df) 251 | } 252 | 253 | 254 | ###take out entries commanded to delete 255 | locations.df <- filter(locations.df, namelook!="SKIP") 256 | locations.df[grep('^ID_', names(locations.df))] <- lapply(locations.df[grep('^ID_', names(locations.df))], as.character) 257 | dfname2 <- unique(dfname[,c("namelook", "namelookorig")]) 258 | dfname2[grep('^ID_', names(dfname2))] <- lapply(dfname2[grep('^ID_', names(dfname2))], as.character) 259 | locations.df <- suppressMessages(left_join(locations.df, dfname2[,c("namelook", "namelookorig")])) 260 | 261 | ###little format housekeeping 262 | locations.df$lat <- as.numeric(as.character(locations.df[,"lat"])) 263 | locations.df$lon <- as.numeric(as.character(locations.df[,"lon"])) 264 | locations.df$PN <- gsub('[0-9]','', as.character(locations.df[,"PlacenameGeocoded"])) 265 | locations.df$PN <- gsub(' ,',',', as.character(locations.df[,"PN"])) 266 | locations.df$country <- sub(".*,\\s*([^,]+)$", "\\1", locations.df$PN) 267 | 268 | ###function to get a common country name from country entered 269 | locations.df$CountryName <- standardizeCountry(locations.df$country, fuzzyDist = 25) 270 | 271 | ###function to get iso3 character code from common country name 272 | locations.df$iso3c <- suppressWarnings(invisible(countrycode(locations.df[,"CountryName"], 'country.name', 'iso3c'))) 273 | locations.df[grep('iso3c', names(locations.df))] <- lapply(locations.df[grep('iso3c', names(locations.df))], as.character) 274 | 275 | ###subset list of countries to work with 276 | uni.loc<- locations.df[!duplicated(locations.df$iso3c),] 277 | uni.loc<- uni.loc[!is.na(uni.loc$iso3c),] 278 | 279 | ###Get the lowest gadm level available for each country, from loaded dataframe 280 | ### TOOK OUT gadmlevel=="lowest" | ###I'm 99 percent sure unnecessary, due to smallest.file 281 | if(gadmlevel=="lcl"){ 282 | uni.loc <- suppressMessages(left_join(uni.loc, gadm_levels2[, c("iso3c", "level")])) 283 | mins <- uni.loc[,"level"] 284 | gadmlevel <- min(mins) 285 | } 286 | 287 | n.uniloc <- nrow(uni.loc) 288 | 289 | a <-1 290 | clist <- list() 291 | gadmorig <- gadmlevel 292 | globalgeo <- list() 293 | globalstat <- list() 294 | ###For loop for each country in dataset 295 | for(i in uni.loc[,"iso3c"]){ 296 | ###Defaults of errors on WorldPop and GADM to FALSE 297 | noGADM <- FALSE 298 | gadmlevel <- gadmorig 299 | 300 | dGADM <- file.exists(paste0("gadm",i)) 301 | ###Download and unzip GADM if exists 302 | if(!isTRUE(orideGADM) & !isTRUE(dGADM)){ 303 | writeLines(c("",paste0("Currently DOWNLOADING the GADM file for: ", uni.loc[a,"CountryName"] ))) 304 | gadmresp <- tryCatch(GET( 305 | url = paste0("http://biogeo.ucdavis.edu/data/gadm2.8/shp/", i,"_adm_shp.zip"), 306 | progress(), 307 | write_disk(paste0("gadm",i,".zip"), overwrite=TRUE) 308 | )-> gadmresp, 309 | error=function(e){noGADM <- TRUE}) 310 | if(!isTRUE(gadmresp)){gadmresp <- FALSE} 311 | if(!isTRUE(noGADM) & !isTRUE(gadmresp)){unzip(paste0("gadm",i,".zip"), exdir=paste0("gadm",i), overwrite=TRUE)} 312 | } 313 | 314 | ###Get the lowest GADM layer to overlay. Lowest layers come with higher division codes as well 315 | dGADM <- file.exists(paste0("gadm",i)) 316 | if(isTRUE(dGADM)){ 317 | writeLines(c("",paste0("SHAPEFILE SUCCESS!: ", uni.loc[a,"CountryName"] ))) 318 | 319 | if(is.character(gadmlevel)){ 320 | listfiles <-list.files(paste0("gadm",i,"/")) 321 | 322 | ###Sometimes license.txt gets in the wrong place 323 | listfiles <- gsub("license.txt","aaa.txt", listfiles) 324 | listfiles <- sort(listfiles) 325 | smallest.file <- substr(listfiles[length(listfiles)],8,8) 326 | gadmlevel <- as.numeric(smallest.file) 327 | } 328 | 329 | ###Shapefile read (using sf) 330 | sptemp <- sf::st_read(dsn=paste0("gadm",i), layer=paste0(i,"_adm",gadmlevel), quiet=TRUE) 331 | 332 | flist <- list() 333 | glist <- list() 334 | 335 | 336 | ###Over SF methods for determining dataset locations administrative levels 337 | sp.locations <- locations.df[ which(locations.df$iso3c==i ), ] 338 | sf.locations <- st_as_sf(sp.locations, coords=c("lon","lat"), crs= 4326) 339 | over <- suppressWarnings(suppressMessages(st_intersection(sf.locations,sptemp))) 340 | st_geometry(over) <- NULL 341 | over <- suppressMessages(left_join(over, sptemp[,c(paste0("ID_",gadmlevel), "geometry")])) 342 | sp.locations <- as.data.frame(sp.locations) 343 | df.loc <- bind_cols(sp.locations[,c("lat", "lon")], over) 344 | 345 | 346 | 347 | ### Took out df.loc<- suppressMessages(suppressWarnings(left_join(sp.locations, over))) 348 | 349 | df.loc[grep('^ID_', names(df.loc))] <- lapply(df.loc[grep('^ID_', names(df.loc))], as.character) 350 | df.loc[grep('iso3c', names(df.loc))] <- lapply(df.loc[grep('iso3c', names(df.loc))], as.character) 351 | ##get area and modify format 352 | df.loc$area_a <- st_area(df.loc$geometry) 353 | df.loc$area_a <- as.numeric(df.loc$area_a) 354 | df.loc$area_a_sqkm <- df.loc[,"area_a"]/1000000 355 | df.loc[grep('^ID_', names(df.loc))] <- lapply(df.loc[grep('^ID_', names(df.loc))], as.character) 356 | 357 | justid <- df.loc[ , grepl( "ID_" , colnames( df.loc ) ) ] 358 | 359 | flist[[1]] <- cbind(justid, df.loc[,c("area_a", "area_a_sqkm", "geometry")]) 360 | glist[[1]] <- cbind(justid, df.loc[,c("namelook", "PlacenameGeocoded", "lat", "lon", 361 | "CountryName", "iso3c", "area_a", "area_a_sqkm")]) 362 | 363 | colnames(flist[[1]])[colnames(flist[[1]])=='geometry'] <- paste0("geometry",gadmlevel) 364 | colnames(flist[[1]])[colnames(flist[[1]])=='area_a'] <- paste0("area_",gadmlevel,"_Msq") 365 | colnames(flist[[1]])[colnames(flist[[1]])=='area_a_sqkm'] <- paste0("area_",gadmlevel,"_KMsq") 366 | 367 | colnames(glist[[1]])[colnames(glist[[1]])=='geometry'] <- paste0("geometry",gadmlevel) 368 | colnames(glist[[1]])[colnames(glist[[1]])=='area_a'] <- paste0("area_",gadmlevel,"_Msq") 369 | colnames(glist[[1]])[colnames(glist[[1]])=='area_a_sqkm'] <- paste0("area_",gadmlevel,"_KMsq") 370 | 371 | if(isTRUE(fill)){ 372 | rgadmlevel <- gadmlevel 373 | rr <-2 374 | repeat{ 375 | rgadmlevel <- rgadmlevel - 1 376 | if(rgadmlevel<0){break} 377 | sptemp <- suppressWarnings(sf::st_read(dsn=paste0("gadm",i), layer=paste0(i,"_adm",rgadmlevel), quiet=TRUE)) 378 | over <- suppressWarnings(suppressMessages(st_intersection(sf.locations,sptemp))) 379 | over <- over[,c(paste0("ID_",rgadmlevel))] 380 | st_geometry(over) <- NULL 381 | over <- unique(over) 382 | over <- suppressMessages(left_join(over, sptemp[,c(paste0("ID_",rgadmlevel), "geometry")])) 383 | over[grep('^ID_', names(over))] <- lapply(over[grep('^ID_', names(over))], as.character) 384 | over$area_a <- st_area(over$geometry) 385 | over$area_a <- as.numeric(over$area_a) 386 | over$area_a_sqkm <- over[,"area_a"]/1000000 387 | ### dont think need this: over <- suppressMessages(left_join(over, df.loc[,c(paste0("ID_",rgadmlevel),"namelook")])) 388 | colnames(over)[colnames(over)=='geometry'] <- paste0("geometry",rgadmlevel) 389 | colnames(over)[colnames(over)=='area_a'] <- paste0("area_",rgadmlevel,"_Msq") 390 | colnames(over)[colnames(over)=='area_a_sqkm'] <- paste0("area_",rgadmlevel,"_KMsq") 391 | gover <- over[,c(1, 3, 4)] 392 | flist[[rr]]<- over 393 | glist[[rr]]<- gover 394 | rr <- rr+1 395 | } 396 | } 397 | } 398 | globalgeo[[a]] <- flist 399 | globalstat[[a]] <- glist 400 | a <- a+1 401 | ###Delete GADM shapefile in disk space (wd) if default deleteGADM=TRUE. Used for all extraction already 402 | if(isTRUE(deleteGADM) & isTRUE(dGADM)){ 403 | file.remove(paste0("gadm",i,".zip")) 404 | unlink(paste0("gadm",i, "/*")) 405 | file.remove(paste0("gadm",i,"/")) 406 | } 407 | } 408 | MASTERstat <- list() 409 | foreach(p=1:length(globalstat))%do%{ 410 | MASTERstat[[p]] <- suppressMessages(Reduce(left_join, globalstat[[p]])) 411 | } 412 | MASTERstat <- suppressWarnings(do.call("bind_rows",MASTERstat)) 413 | 414 | ###MASTERgeo <<- globalgeo 415 | foreach(g=1:length(globalgeo))%do%{ 416 | n.lgg <- length(globalgeo[[g]]) 417 | globalgeo[[g]][[n.lgg]] <- suppressMessages(inner_join(globalgeo[[g]][[n.lgg]], 418 | as.data.frame(unique(MASTERstat[,c("ID_0", "CountryName")])))) 419 | checkin1 <<- TRUE 420 | } 421 | MASTERgeo <<- globalgeo 422 | colnames(MASTERstat) <- paste("sp", colnames(MASTERstat), sep="_") 423 | colnames(MASTERstat)[colnames(MASTERstat)=="sp_namelook"] <- "namelook" 424 | MASTERstat <<- MASTERstat 425 | MASTERout <<- suppressMessages(left_join(dfname, MASTERstat)) 426 | writeLines(c("",green("Written to Global Environment:"), 427 | "MASTERgeo is your list of geometries. Use it for extraction functions.", 428 | "MASTERout is your dataset bound with newly attached geocoding.", 429 | "MASTERstat is your dataset of unique locations in the dataset, unbound.")) 430 | 431 | 432 | } 433 | 434 | 435 | 436 | 437 | 438 | 439 | 440 | 441 | 442 | 443 | 444 | -------------------------------------------------------------------------------- /R/spheatNames_dep.R: -------------------------------------------------------------------------------- 1 | #' DEPRECIATED: NEW FUNCTION IS spheatNAMES() Geocode place names in a dataset 2 | #' 3 | #' geocode a vector of names in a dataset with administrative layers determined 4 | #' by GADM layers 5 | #' 6 | #' 7 | #' @param dataset (character), the name of the data frame containing a column 8 | #' of place names. e.g. \code{“mydataframe”} 9 | #' @param colname (character), the name of the column in the data frame 10 | #' containing place names e.g. \code{“mycolname”} 11 | #' @param googleapikey (character), a valid Google Maps API key. See 12 | #' https://developers.google.com/maps/documentation/javascript/get-api-key to 13 | #' attain one. 14 | #' @param oride (logical), if you already have the specified shapefile 15 | #' downloads from GADM for each country in your data frame, you may override 16 | #' the GADM downloads included in a-heat using oride=TRUE. ONLY do this if you 17 | #' are sure you have the GADM shapefiles for every country in your set already 18 | #' in your R working directory. Default is oride=FALSE 19 | #' @param deleteGADM (logical), if after geocoding you would like to keep the 20 | #' GADM shapefiles downloaded in your working directory you may use 21 | #' deleteGADM=FALSE. The files can be large, especially if you have many 22 | #' countries in your dataset. Use carefully, could cause many large GADM 23 | #' shapefiles saved to your working directory. The default is deleteGADM=TRUE. 24 | #' 25 | #' 26 | #' 27 | #' @author Neal Thomas Barsch 28 | #' @references GADM DATA are attained through the GADM project website. 29 | #' Commercial use of this function is not allowed without prior permission from 30 | #' GADM.org. \url{http://gadm.org/}. 31 | #' @examples 32 | #' 33 | #' 34 | #' spheatNames_dep("myDataframe", "myColWithPlaceNames", "mygoogleapikey") 35 | #' 36 | #' #Keeping all GADM shapefiles 37 | #' spheatNames_dep("myDataframe", "myColWithPlaceNames", "mygoogleapikey", deleteGADM=FALSE) 38 | #' 39 | #' #You already have the GADM shapefiles and don't want to redownload or delete them 40 | #' spheatNames_dep("myDataframe", "myColWithPlaceNames", "mygoogleapikey", oride=TRUE, deleteGADM=FALSE) 41 | #' 42 | #' 43 | #' @export spheatNames_dep 44 | spheatNames_dep <- function (dataset, colname, googleapikey, oride=FALSE, deleteGADM=TRUE) { 45 | replacebug <-"n" 46 | dfname <- get(dataset) 47 | dfname$namelook <- as.character(dfname[,paste0(colname)]) 48 | dfname$namelook <- gsub(' ','',dfname[,"namelook"]) 49 | lookcol <- dfname[,"namelook"] 50 | lookcol <- as.data.frame(lookcol) 51 | colnames(lookcol) <- "lookcol" 52 | lookcol$lookcol <- as.character(lookcol[,"lookcol"]) 53 | lookcol <- lookcol[!(is.na(lookcol[,"lookcol"]) | lookcol[,"lookcol"]==""),] 54 | lookVector <- unique(lookcol) 55 | iters.look <- length(lookVector) 56 | pb = txtProgressBar(min = 0, max = iters.look, initial = 0, style=3) 57 | print(paste("...Geocoding your locations in dataset, please wait...")) 58 | locations.df <- foreach(a=1:iters.look, .combine=rbind) %do% { 59 | setTxtProgressBar(pb,a) 60 | if(lookVector[a]=="NewYork,NewYork"){ 61 | replacebug <- lookVector[a] 62 | lookVector[a] <- gsub('NewYork,NewYork','Empire State Building',lookVector[a]) 63 | } 64 | gway.df <- google_geocode(paste(lookVector[a]),key=googleapikey) 65 | if(gway.df$status=="ZERO_RESULTS"){ 66 | print(paste0("...Could not find entry: ", lookVector[a])) 67 | uinput.newname <- readline(prompt="Replace with manual entry: ") 68 | uinput.newname <- gsub(' ','',uinput.newname) 69 | dfname$namelook <- gsub(paste(lookVector[a]), paste(uinput.newname), dfname[,"namelook"]) 70 | lookVector[a] <- uinput.newname 71 | gway.df <- google_geocode(paste(lookVector[a]),key=googleapikey) 72 | rm(uinput.newname) 73 | } 74 | gway.df<- unlist(gway.df) 75 | gway.df<- as.data.frame(gway.df) 76 | gway.df <- as.data.frame(gway.df[c("results.geometry.location.lat","results.geometry.location.lng","results.formatted_address"), "gway.df"]) 77 | colnames(gway.df)<-"gway" 78 | gway.df <- t(gway.df) 79 | gway.df <- data.frame(r1= row.names(gway.df), gway.df, row.names=NULL) 80 | if(replacebug=="NewYork,NewYork"){ 81 | lookVector[a]<-replacebug 82 | } 83 | gway.df$namelook <- lookVector[a] 84 | gway.df <- gway.df[,2:ncol(gway.df)] 85 | colnames(gway.df) <- c("lat", "lon","PlacenameGeocoded", "namelook") 86 | replacebug <-"n" 87 | gway.df 88 | } 89 | locations.df$lat <- as.numeric(as.character(locations.df[,"lat"])) 90 | locations.df$lon <- as.numeric(as.character(locations.df[,"lon"])) 91 | locations.df$PN <- gsub('[0-9]','', as.character(locations.df[,"PlacenameGeocoded"])) 92 | locations.df$PN <- gsub(' ,',',', as.character(locations.df[,"PN"])) 93 | locations.df$country <- sub(".*,\\s*([^,]+)$", "\\1", locations.df$PN) 94 | locations.df$iso3c <- countrycode(locations.df[,"country"], 'country.name', 'iso3c') 95 | uni.loc<- subset(locations.df, !duplicated(iso3c)) 96 | uni.loc<- subset(uni.loc, !is.na(iso3c)) 97 | a <-1 98 | clist <- list() 99 | pb = txtProgressBar(min = 0, max = nrow(uni.loc), initial = 0, style=3) 100 | for(i in uni.loc[,"iso3c"]){ 101 | if(oride!=TRUE){ 102 | curl_download(paste0("http://biogeo.ucdavis.edu/data/gadm2.8/shp/", i,"_adm_shp.zip"), 103 | destfile=paste0("gadm",i,".zip")) 104 | unzip(paste0("gadm",i,".zip"), exdir=paste0("gadm",i), overwrite=TRUE) 105 | } 106 | listfiles <-list.files(paste0("gadm",i,"/")) 107 | listfiles <- gsub("license.txt","aaa.txt", listfiles) 108 | listfiles <- sort(listfiles) 109 | smallest.file <- substr(listfiles[length(listfiles)],8,8) 110 | sptemp <- readOGR(dsn=paste0("gadm",i), layer=paste0(i,"_adm",smallest.file)) 111 | sp.locations <- locations.df[ which(locations.df$iso3c==i ), ] 112 | coordinates(sp.locations) <- ~lon+lat 113 | proj4string(sp.locations)=CRS("+proj=longlat +datum=WGS84 +no_defs +ellps=WGS84 +towgs84=0,0,0") 114 | over <- over(sp.locations,sptemp) 115 | sp.locations <- as.data.frame(sp.locations) 116 | clist[[a]] <- data.frame(sp.locations, over) 117 | clist[[a]] <- lapply(clist[[a]], as.character) 118 | setTxtProgressBar(pb,a) 119 | a <- a+1 120 | if(deleteGADM==TRUE){ 121 | file.remove(paste0("gadm",i,".zip")) 122 | unlink(paste0("gadm",i, "/*")) 123 | file.remove(paste0("gadm",i,"/")) 124 | } 125 | } 126 | masterloc <- do.call("bind_rows",clist) 127 | masterloc <- as.data.frame(masterloc) 128 | masterloc$lat <- as.numeric(masterloc[,"lat"]) 129 | masterloc$lon <- as.numeric(masterloc[,"lon"]) 130 | masterloc$latlong <- paste0(masterloc[,"lat"],"-",masterloc[,"lon"]) 131 | masterout<- left_join(dfname,masterloc, by="namelook") 132 | masterout <- masterout[, colSums(is.na(masterout)) != nrow(masterout)] 133 | MASTER_Names <<- masterout 134 | } 135 | 136 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # spaceheater 2 | 3 | ```spaceheater``` is an `R` package that allows easy and flexible adding of a variety of spatial variables to any geocoded (lat/lon) dataset. 4 | 5 | ```spaceheater``` is built to be fully automatic by downloading and completing advanced spatial analysis without requiring advanced coding capability by the user. This enables a wider research audience to be able to utilize advanced spatial controls previously only available to advanced users. 6 | 7 | ```spheatNAMES``` and ```spheatGPS``` are fully functional. WorldPop download and option/datatype lookups are all fully functional. The WorldPop extraction code is in beta but should be functional, please report any issues. Upcoming extraction codes that should be available within the next few months include NASA MODIS Satellite layers, NASA NOAA Nightlights layers, and OPEN STREET MAPS road density calculation. 8 | 9 | Example WorldPop tif that Spaceheater can download and analyze (from WorldPop UK): 10 | 11 | ![Data](/SpaceheaterExampleBangladesh.png?raw=true "Spaceheater Data") 12 | 13 | ## Installation 14 | 15 | ```r 16 | if (!require(remotes)) install.packages("remotes") 17 | remotes::install_github("nbarsch/spaceheater") 18 | ``` 19 | 20 | ## Usage 21 | ```spaceheater``` can be used with it's built in spatial data downloads as a standalone (i.e. the ```getWPdownload()``` function) -OR- may be used in fully automatic mode by using the SPheat() commands. 22 | 23 | ## To Complete Extraction of Spatial Data you must geocode your dataset with spaceheater 24 | 1. ```spheatNAMES()```: if you have a column with any type of place NAMES (addresses, states, cities, counties, villages, etc.). Input type is very flexible and can be mixed within the location column. 25 | 2. ```spheatGPS()```: if you have a LATITUDE COLUMN and LONGITUDE COLUMN in your dataset. 26 | 3. ```spheatLOOKUP()```: if you want to manually enter place names and create a dataset from scratch (upcoming update, only depreciated available). 27 | 28 | Using spheatNAMES, spheatGPS, or spheatLOOKUP: 29 | 30 | ```spheatNAMES(dataset=my_df_name, colname="my_column_of_place_names", googleapikey="my_Google_API_Key")``` 31 | 32 | ```spheatGPS(dataset=my_df_name, latcol="my_column_of_latitudes", loncol="my_column_of_latitudes", googleapikey="my_Google_API_Key")``` 33 | 34 | ##Upcoming not currently available (depreciated geocoder lookup available through spheatLookup_dep, but does NOT work with extraction functions) 35 | 36 | ```spheatLOOKUP("my_Google_API_Key")``` 37 | 38 | 39 | ## Extraction 40 | 41 | Complete Extraction ONLY AFTER completing one of the spheat functions 42 | 43 | Currently (January 2019) extract code for WorldPop UK rasters are available 44 | 45 | ```extractWP(datatype="Births", options="pp", year=2015, gadmlevel="lowest", fill=TRUE, deleteRAST=TRUE)``` 46 | 47 | ```extractWP(datatype="Population", options=c("ppp", "adj"), year=2010, gadmlevel="lowest", fill=TRUE, deleteRAST=TRUE)``` 48 | 49 | You dont want to delete the Raster files (warning, could take a lot of storage space if not deleted) 50 | 51 | ```extractWP(datatype="Births", options="pp", year=2015,deleteRAST=FALSE)``` 52 | 53 | 54 | ## Lookup of what is available from WorldPop also available: 55 | 56 | Get the possible tif sets from WorldPop UK for Bangladesh 57 | 58 | ```getWPdatatypes("Bangladesh")``` 59 | 60 | Get the possible options for tif sets from WorldPop UK for Tanzania Population sets 61 | 62 | ```getWPoptions("Bangladesh", "Population")``` 63 | 64 | Manual download of WP (happens automatically in extract code) also available: 65 | Download the 2010 Persons per pixel, adjusted to match UN estimates tif for Bangladesh from WorldPop UK 66 | 67 | ```getWPdownload("Bangladesh", "Population", c("ppp", "adj"), 2010)``` 68 | 69 | 70 | 71 | 72 | 73 | 74 | 75 | -------------------------------------------------------------------------------- /SpaceheaterExampleBangladesh.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nbarsch/spaceheater/5ccada3edd47bb0e1bfd5774df59e774905a6217/SpaceheaterExampleBangladesh.png -------------------------------------------------------------------------------- /data/.DS_Store: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nbarsch/spaceheater/5ccada3edd47bb0e1bfd5774df59e774905a6217/data/.DS_Store -------------------------------------------------------------------------------- /data/gadm_levels28.RData: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nbarsch/spaceheater/5ccada3edd47bb0e1bfd5774df59e774905a6217/data/gadm_levels28.RData -------------------------------------------------------------------------------- /man/extractWP.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/extractWP.R 3 | \name{extractWP} 4 | \alias{extractWP} 5 | \title{Extract WorldPop UK Raster Sets for all locations from a spheated dataset.} 6 | \usage{ 7 | extractWP(datatype, options, year, gadmlevel = "lowest", fill = TRUE, 8 | deleteRAST = TRUE, outdata = MASTERout, geolist = MASTERgeo) 9 | } 10 | \arguments{ 11 | \item{datatype}{(character), the datatype you would like to see what options 12 | are available for WorldPop UK data. The available datatypes can be attained 13 | with the function getWPdatatypes() Example datatypes: \code{“Population”} or 14 | \code{“Stunting”}} 15 | 16 | \item{options}{(character), the options of the tif dataset you would like to 17 | download. The available options can be attained with the function 18 | getWPoptions() e.g. \code{“ppp”} or \code{c(“F”, "interdecile")}} 19 | 20 | \item{year}{(numeric), the year of the dataset you would like to download. 21 | Available years are given by the getWPoptions() function for any given country.} 22 | 23 | \item{gadmlevel}{(integer or character), either an integer level gadm level to extract for all countries in MASTERout, or one of 24 | \code{gadmlevel="lowest"} for the lowest respective gadm level available 25 | or \code{gadmlevel="lcl"} for lowest COMMON level among all countries in MASTERout. 26 | Default is \code{gadmlevel="lowest"}} 27 | 28 | \item{fill}{(logical), if extraction values for all higher gadm geographic level values should also be returned. 29 | I.e. if gadmlevel=3 and fill=TRUE, extractWP will return the extraction values for gadm levels 0, 1, 2, and 3. 30 | If fill=FALSE in this case, extractWP will only return extraction values for gadm level 3. 31 | See gadm.org for details about levels (in short level 0 is always country, 1 is state/province/equivalent, 32 | 2 is county/municipality/equivalent, 3 is village/equivalent, 4 and more get into blocks and other lower geographic levels). 33 | Default is \code{fill=TRUE}} 34 | 35 | \item{deleteRAST}{(logical), logical if the downloaded WorldPop UK Raster sets should be deleted when they are done being analyzed. 36 | Reccomended TRUE for datasets containing many countries as TRUE deletes the done analyzed raster 37 | before a new one is downloaded, minimizing disk space use. 38 | Default is \code{deleteRAST=TRUE}} 39 | } 40 | \description{ 41 | You must have run an spheat function (spheatNAMES, spheatGPS, or spheatLOOKUP) 42 | to exercise this function. 43 | } 44 | \examples{ 45 | 46 | extractWP(datatype="Births", options="pp", year=2015, gadmlevel="lowest", fill=TRUE, deleteRAST=TRUE) 47 | 48 | extractWP(datatype="Population", options=c("ppp", "adj"), year=2010, gadmlevel="lowest", fill=TRUE, deleteRAST=TRUE) 49 | 50 | #You dont want to delete the Raster files (warning, could take a lot of storage space if not deleted) 51 | extractWP(datatype="Births", options="pp", year=2015,deleteRAST=FALSE) 52 | 53 | 54 | } 55 | \references{ 56 | GADM DATA are attained through the GADM project website. 57 | Commercial use of this function is not allowed without prior permission from 58 | GADM.org. \url{http://gadm.org/}. 59 | 60 | WorldPop UK data are attained through the WorldPop UK website. 61 | These data are licensensed under the Creative Commons Attribution 4.0 62 | License. \url{http://www.worldpop.org.uk/}. 63 | 64 | Eternal grattitude to StackOverflow member hrbrmstr who contributed crucially 65 | to the code for the downloads from WorldPop. 66 | } 67 | \author{ 68 | Neal Thomas Barsch 69 | } 70 | -------------------------------------------------------------------------------- /man/getWPdatatypes.Rd: -------------------------------------------------------------------------------- 1 | \name{getWPdatatypes} 2 | 3 | \alias{getWPdatatypes} 4 | 5 | \title{Get the available datatypes for a country from WorldPop UK datasets} 6 | 7 | \description{This function pulls what are the available datatypes from WorldPop UK for a given country. It returns a not available message if the country typed does not exist on WorldPop. As a bonus and to make matching WorldPop sets easier, this function contains correction algorithms to standardize country names to match WorldPop UK sets (i.e. WorldPop has "Côte d'Ivoire", you can type "Ivory Coast" and it will return the WorldPop Côte d'Ivoire set). This function adds a dataframe of the available sets called WPdata.types to your working environment.} 8 | 9 | \usage{ 10 | getWPdatatypes(countryname)} 11 | 12 | \arguments{ 13 | 14 | \item{countryname}{(character), the name of a country you want to see what data is avaialble from WorldPop for. e.g. \code{“Tanzania”} 15 | } 16 | } 17 | 18 | \examples{ 19 | 20 | getWPdatatypes("Nigeria") 21 | } 22 | 23 | \references{ 24 | WorldPop UK data are attained through the WorldPop UK website. These data are licensensed under the Creative Commons Attribution 4.0 License. 25 | \url{http://www.worldpop.org.uk/}. 26 | 27 | Eternal grattitude to StackOverflow member hrbrmstr without whom this function would not have been possible. 28 | } 29 | \author{ 30 | Neal Thomas Barsch 31 | } 32 | 33 | 34 | -------------------------------------------------------------------------------- /man/getWPdownload.Rd: -------------------------------------------------------------------------------- 1 | \name{getWPdownload} 2 | 3 | \alias{getWPdownload} 4 | 5 | \title{Download a dataset from the WorldPopUK site} 6 | 7 | \description{This function downloads a dataset in .tif format from the WorldPopUK 8 | 9 | This function is intended to be used following the getWPdatatypes() and getWPoptions() functions as the inputs for getWPdownload() are given by the previous two functions. 10 | 11 | As a bonus and to make matching WorldPop sets easier, this function contains correction algorithms to standardize country names to match WorldPop UK sets (i.e. WorldPop has "Côte d'Ivoire", you can type "Ivory Coast" and it will return the WorldPop Côte d'Ivoire set). This function adds a dataframe of the available sets called WP.options to your working environment.} 12 | 13 | \usage{ 14 | getWPdownload(countryname, datatype, options, year)} 15 | 16 | \arguments{ 17 | 18 | \item{countryname}{(character), the name of a country you want to see what data is avaialble from WorldPop for. e.g. \code{“Tanzania”} 19 | } 20 | \item{datatype}{(character), the datatype you would like to see what options are available for WorldPop UK data. The available datatypes can be attained with the function getWPdatatypes() Example datatypes: \code{“Population”} or \code{“Stunting”} 21 | } 22 | \item{options}{(character), the options of the tif dataset you would like to download. The available options can be attained with the function getWPoptions() e.g. \code{“ppp”} or \code{c(“F”, "interdecile")} 23 | } 24 | \item{year}{(numeric), the year of the dataset you would like to download. Available years are given by the getWPoptions() function. 25 | 26 | If a dataset on WorldPop is not year coded in the filename you will need to type 9999 for the year. This is indicated by the getWPoptions() function. e.g. \code{2015} or \code{9999} 27 | } 28 | 29 | } 30 | 31 | \examples{ 32 | 33 | getWPdownload("Tanzania", "Births", "pp", 2015) 34 | 35 | #Example that has year 9999 and multiple options 36 | getWPdownload("Nigeria", "Stunting", c("F", "interdecile"), 9999) 37 | 38 | ###FULL EXAMPLES### 39 | 40 | ###Full Example 1### 41 | #see available Tanzania sets 42 | getWPdatatypes("Tanzania") 43 | 44 | #see available options for Tanzania Births Set 45 | getWPoptions("Tanzania", "Births") 46 | 47 | #Download as above with included options 48 | getWPdownload("Tanzania", "Births", "pp", 2015) 49 | 50 | ###Full Example 2### 51 | getWPdatatypes("Nigeria") 52 | 53 | #see available options for Nigeria Stunting Set 54 | getWPoptions("Nigeria", "Stunting") 55 | 56 | #Download as above with included options for uncertainty map 57 | getWPdownload("Nigeria", "Stunting", c("F", "interdecile"), 9999) 58 | 59 | #or for the dataset NOT the uncertainty map 60 | getWPdownload("Nigeria", "Stunting", "F", 9999) 61 | 62 | 63 | 64 | } 65 | 66 | \references{ 67 | WorldPop UK data are attained through the WorldPop UK website. These data are licensensed under the Creative Commons Attribution 4.0 License. 68 | \url{http://www.worldpop.org.uk/}. 69 | 70 | Eternal grattitude to StackOverflow member hrbrmstr without whom this function would not have been possible. 71 | } 72 | \author{ 73 | Neal Thomas Barsch 74 | } 75 | 76 | 77 | -------------------------------------------------------------------------------- /man/getWPoptions.Rd: -------------------------------------------------------------------------------- 1 | \name{getWPoptions} 2 | 3 | \alias{getWPoptions} 4 | 5 | \title{Get the available options for a country and datatype set from WorldPopUK} 6 | 7 | \description{This function pulls what are the available datasets from WorldPop UK for a given country and datatype. It returns a not available message if the country typed does not exist on WorldPop. To see the available datatypes for a country, see getWPdatatypes() which is intended to be used before this function. 8 | 9 | Example options returned are "ppp" for persons per pixel, "pph" for persons per hectare, "M" or "F" for male/female tagged sets etc. This function returns all the available options for a given country and datatype. 10 | 11 | The codes returned in the WP.options dataframe in "OptionCode" columns correspond to the options necessary to include in the getWPdownload() function. 12 | 13 | If the function returns the year 9999 in the WP.options dataframe, this means the filename on WorldPop is not year tagged. The year will be included if you look up the set manually on WorldPop UK but for the getWPdownload() function you will need to type 9999 for the year as it corresponds to what is given here. 14 | 15 | As a bonus and to make matching WorldPop sets easier, this function contains correction algorithms to standardize country names to match WorldPop UK sets (i.e. WorldPop has "Côte d'Ivoire", you can type "Ivory Coast" and it will return the WorldPop Côte d'Ivoire set). This function adds a dataframe of the available sets called WP.options to your working environment.} 16 | 17 | \usage{ 18 | getWPoptions(countryname, datatype)} 19 | 20 | \arguments{ 21 | 22 | \item{countryname}{(character), the name of a country you want to see what data is avaialble from WorldPop for. e.g. \code{“Tanzania”} 23 | } 24 | \item{datatype}{(character), the datatype you would like to see what options are available for WorldPop UK data. e.g. \code{“Population”} 25 | } 26 | 27 | } 28 | 29 | \examples{ 30 | 31 | getWPoptions("Tanzania", "Population") 32 | 33 | #Example that returns year 9999 34 | getWPoptions("Nigeria", "Stunting") 35 | } 36 | 37 | \references{ 38 | WorldPop UK data are attained through the WorldPop UK website. These data are licensensed under the Creative Commons Attribution 4.0 License. 39 | \url{http://www.worldpop.org.uk/}. 40 | 41 | Eternal grattitude to StackOverflow member hrbrmstr without whom this function would not have been possible. 42 | } 43 | \author{ 44 | Neal Thomas Barsch 45 | } 46 | -------------------------------------------------------------------------------- /man/spheatGPS.Rd: -------------------------------------------------------------------------------- 1 | \name{spheatGPS} 2 | 3 | \alias{spheatGPS} 4 | 5 | \title{Reverse geocode GPS coordinates in a dataset} 6 | 7 | \description{Reverse geocode latitude and longitude columns in a dataset with administrative layers determined by GADM layers} 8 | 9 | \usage{ 10 | spheatGPS(dataset, latcol, loncol, googleapikey, oride=FALSE, deleteGADM=TRUE)} 11 | 12 | \arguments{ 13 | 14 | \item{dataset}{(character), the name of the data frame containing a column of place names. e.g. \code{“mydataframe”} 15 | } 16 | \item{latcol}{(character), the name of the column in the data frame containing LATITUDES \code{“mylatcol”} 17 | } 18 | \item{loncol}{(character), the name of the column in the data frame containing LONGITUDES \code{“myloncol”} 19 | } 20 | \item{googleapikey}{(character), a valid Google Maps API key. See https://developers.google.com/maps/documentation/javascript/get-api-key to attain one. 21 | } 22 | \item{oride}{(logical), if you already have the specified shapefile downloads from GADM for each country in your data frame, you may override the GADM downloads included in a-heat using oride=TRUE. ONLY do this if you are sure you have the GADM shapefiles for every country in your set already in your R working directory. Default is oride=FALSE 23 | } 24 | \item{deleteGADM}{(logical), if after geocoding you would like to keep the GADM shapefiles downloaded in your working directory you may use deleteGADM=FALSE. The files can be large, especially if you have many countries in your dataset. Use carefully, could cause many large GADM shapefiles saved to your working directory. The default is deleteGADM=TRUE.} 25 | } 26 | 27 | \examples{ 28 | 29 | spheatGPS("myDataframe", "myLatColumnName","myLonColumnName", "mygoogleapikey") 30 | 31 | #Keeping all GADM shapefiles 32 | spheatGPS("myDataframe", "myLatColumnName","myLonColumnName", "mygoogleapikey", deleteGADM=FALSE) 33 | 34 | #You already have the GADM shapefiles and don't want to redownload or delete them 35 | spheatGPS("myDataframe", "myLatColumnName","myLonColumnName", "mygoogleapikey", oride=TRUE, deleteGADM=FALSE) 36 | 37 | } 38 | 39 | \references{ 40 | GADM DATA are attained through the GADM project website. Commercial use of this function is not allowed without prior permission from GADM.org. 41 | \url{http://gadm.org/}. 42 | } 43 | \author{ 44 | Neal Thomas Barsch 45 | } 46 | 47 | 48 | -------------------------------------------------------------------------------- /man/spheatGPS_dep.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/spheatGPS_dep.R 3 | \name{spheatGPS_dep} 4 | \alias{spheatGPS_dep} 5 | \title{DEPRECIATED: NEW FUNCTION IS spheatGPS() 6 | Reverse geocode GPS coordinates in a dataset} 7 | \usage{ 8 | spheatGPS_dep(dataset, latcol, loncol, googleapikey, oride = FALSE, 9 | deleteGADM = TRUE) 10 | } 11 | \arguments{ 12 | \item{dataset}{(character), the name of the data frame containing a column 13 | of place names. e.g. \code{“mydataframe”}} 14 | 15 | \item{latcol}{(character), the name of the column in the data frame 16 | containing LATITUDES \code{“mylatcol”}} 17 | 18 | \item{loncol}{(character), the name of the column in the data frame 19 | containing LONGITUDES \code{“myloncol”}} 20 | 21 | \item{googleapikey}{(character), a valid Google Maps API key. See 22 | https://developers.google.com/maps/documentation/javascript/get-api-key to 23 | attain one.} 24 | 25 | \item{oride}{(logical), if you already have the specified shapefile 26 | downloads from GADM for each country in your data frame, you may override 27 | the GADM downloads included in a-heat using oride=TRUE. ONLY do this if you 28 | are sure you have the GADM shapefiles for every country in your set already 29 | in your R working directory. Default is oride=FALSE} 30 | 31 | \item{deleteGADM}{(logical), if after geocoding you would like to keep the 32 | GADM shapefiles downloaded in your working directory you may use 33 | deleteGADM=FALSE. The files can be large, especially if you have many 34 | countries in your dataset. Use carefully, could cause many large GADM 35 | shapefiles saved to your working directory. The default is deleteGADM=TRUE.} 36 | } 37 | \description{ 38 | Reverse geocode latitude and longitude columns in a dataset with 39 | administrative layers determined by GADM layers 40 | } 41 | \examples{ 42 | 43 | 44 | spheatGPS_dep("myDataframe", "myLatColumnName","myLonColumnName", "mygoogleapikey") 45 | 46 | #Keeping all GADM shapefiles 47 | spheatGPS_dep("myDataframe", "myLatColumnName","myLonColumnName", "mygoogleapikey", deleteGADM=FALSE) 48 | 49 | #You already have the GADM shapefiles and don't want to redownload or delete them 50 | spheatGPS_dep("myDataframe", "myLatColumnName","myLonColumnName", "mygoogleapikey", oride=TRUE, deleteGADM=FALSE) 51 | 52 | 53 | } 54 | \references{ 55 | GADM DATA are attained through the GADM project website. 56 | Commercial use of this function is not allowed without prior permission from 57 | GADM.org. \url{http://gadm.org/}. 58 | } 59 | \author{ 60 | Neal Thomas Barsch 61 | } 62 | -------------------------------------------------------------------------------- /man/spheatLookup.Rd: -------------------------------------------------------------------------------- 1 | \name{spheatLookup} 2 | 3 | \alias{spheatLookup} 4 | 5 | \title{Geocode a list of places manually typed into the function in a loop} 6 | 7 | \description{Geocode a list of places manually typed into spaceheater in a loop with administrative layers determined by GADM layers. The function will prompt the user to type place names until the user is finished (indicated by typing DONE). The function returns a dataframe of all typed locations with GADM administrative levels and GPS coordinates. This function is only useful if your locations are not already in a data frame, see spheatNames() if you already have locations in data frame format.} 8 | 9 | \usage{ 10 | spheatLookup(googleapikey, oride=FALSE, deleteGADM=TRUE)} 11 | 12 | \arguments{ 13 | 14 | \item{googleapikey}{(character), a valid Google Maps API key. See https://developers.google.com/maps/documentation/javascript/get-api-key to attain one. 15 | } 16 | \item{oride}{(logical), if you already have the specified shapefile downloads from GADM for each country in your data frame, you may override the GADM downloads included in a-heat using oride=TRUE. ONLY do this if you are sure you have the GADM shapefiles for every country in your set already in your R working directory. Default is oride=FALSE 17 | } 18 | \item{deleteGADM}{(logical), if after geocoding you would like to keep the GADM shapefiles downloaded in your working directory you may use deleteGADM=FALSE. The files can be large, especially if you have many countries in your dataset. Use carefully, could cause many large GADM shapefiles saved to your working directory. The default is deleteGADM=TRUE.} 19 | } 20 | 21 | \examples{ 22 | 23 | spheatLookup("mygoogleapikey") 24 | 25 | #Keeping all GADM shapefiles 26 | spheatLookup("mygoogleapikey", deleteGADM=FALSE) 27 | 28 | #You already have the GADM shapefiles and don't want to redownload or delete them 29 | spheatLookup("mygoogleapikey", oride=TRUE, deleteGADM=FALSE) 30 | 31 | } 32 | 33 | \references{ 34 | GADM DATA are attained through the GADM project website. Commercial use of this function is not allowed without prior permission from GADM.org. 35 | \url{http://gadm.org/}. 36 | } 37 | \author{ 38 | Neal Thomas Barsch 39 | } 40 | 41 | 42 | -------------------------------------------------------------------------------- /man/spheatNames.Rd: -------------------------------------------------------------------------------- 1 | \name{spheatNames} 2 | 3 | \alias{spheatNames} 4 | 5 | \title{Geocode place names in a dataset} 6 | 7 | \description{geocode a vector of names in a dataset with administrative layers determined by GADM layers} 8 | 9 | \usage{ 10 | spheatNames(dataset, colname, googleapikey, oride=FALSE, deleteGADM=TRUE)} 11 | 12 | \arguments{ 13 | 14 | \item{dataset}{(character), the name of the data frame containing a column of place names. e.g. \code{“mydataframe”} 15 | } 16 | \item{colname}{(character), the name of the column in the data frame containing place names e.g. \code{“mycolname”} 17 | } 18 | \item{googleapikey}{(character), a valid Google Maps API key. See https://developers.google.com/maps/documentation/javascript/get-api-key to attain one. 19 | } 20 | \item{oride}{(logical), if you already have the specified shapefile downloads from GADM for each country in your data frame, you may override the GADM downloads included in a-heat using oride=TRUE. ONLY do this if you are sure you have the GADM shapefiles for every country in your set already in your R working directory. Default is oride=FALSE 21 | } 22 | \item{deleteGADM}{(logical), if after geocoding you would like to keep the GADM shapefiles downloaded in your working directory you may use deleteGADM=FALSE. The files can be large, especially if you have many countries in your dataset. Use carefully, could cause many large GADM shapefiles saved to your working directory. The default is deleteGADM=TRUE.} 23 | } 24 | 25 | \examples{ 26 | 27 | spheatNames("myDataframe", "myColWithPlaceNames", "mygoogleapikey") 28 | 29 | #Keeping all GADM shapefiles 30 | spheatNames("myDataframe", "myColWithPlaceNames", "mygoogleapikey", deleteGADM=FALSE) 31 | 32 | #You already have the GADM shapefiles and don't want to redownload or delete them 33 | spheatNames("myDataframe", "myColWithPlaceNames", "mygoogleapikey", oride=TRUE, deleteGADM=FALSE) 34 | 35 | } 36 | 37 | 38 | \references{ 39 | GADM DATA are attained through the GADM project website. Commercial use of this function is not allowed without prior permission from GADM.org. 40 | \url{http://gadm.org/}. 41 | } 42 | \author{ 43 | Neal Thomas Barsch 44 | } 45 | 46 | 47 | -------------------------------------------------------------------------------- /man/spheatNames_dep.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/spheatNames_dep.R 3 | \name{spheatNames_dep} 4 | \alias{spheatNames_dep} 5 | \title{DEPRECIATED: NEW FUNCTION IS spheatNAMES() Geocode place names in a dataset} 6 | \usage{ 7 | spheatNames_dep(dataset, colname, googleapikey, oride = FALSE, 8 | deleteGADM = TRUE) 9 | } 10 | \arguments{ 11 | \item{dataset}{(character), the name of the data frame containing a column 12 | of place names. e.g. \code{“mydataframe”}} 13 | 14 | \item{colname}{(character), the name of the column in the data frame 15 | containing place names e.g. \code{“mycolname”}} 16 | 17 | \item{googleapikey}{(character), a valid Google Maps API key. See 18 | https://developers.google.com/maps/documentation/javascript/get-api-key to 19 | attain one.} 20 | 21 | \item{oride}{(logical), if you already have the specified shapefile 22 | downloads from GADM for each country in your data frame, you may override 23 | the GADM downloads included in a-heat using oride=TRUE. ONLY do this if you 24 | are sure you have the GADM shapefiles for every country in your set already 25 | in your R working directory. Default is oride=FALSE} 26 | 27 | \item{deleteGADM}{(logical), if after geocoding you would like to keep the 28 | GADM shapefiles downloaded in your working directory you may use 29 | deleteGADM=FALSE. The files can be large, especially if you have many 30 | countries in your dataset. Use carefully, could cause many large GADM 31 | shapefiles saved to your working directory. The default is deleteGADM=TRUE.} 32 | } 33 | \description{ 34 | geocode a vector of names in a dataset with administrative layers determined 35 | by GADM layers 36 | } 37 | \examples{ 38 | 39 | 40 | spheatNames_dep("myDataframe", "myColWithPlaceNames", "mygoogleapikey") 41 | 42 | #Keeping all GADM shapefiles 43 | spheatNames_dep("myDataframe", "myColWithPlaceNames", "mygoogleapikey", deleteGADM=FALSE) 44 | 45 | #You already have the GADM shapefiles and don't want to redownload or delete them 46 | spheatNames_dep("myDataframe", "myColWithPlaceNames", "mygoogleapikey", oride=TRUE, deleteGADM=FALSE) 47 | 48 | 49 | } 50 | \references{ 51 | GADM DATA are attained through the GADM project website. 52 | Commercial use of this function is not allowed without prior permission from 53 | GADM.org. \url{http://gadm.org/}. 54 | } 55 | \author{ 56 | Neal Thomas Barsch 57 | } 58 | -------------------------------------------------------------------------------- /spaceheater.Rproj: -------------------------------------------------------------------------------- 1 | Version: 1.0 2 | 3 | RestoreWorkspace: Default 4 | SaveWorkspace: Default 5 | AlwaysSaveHistory: Default 6 | 7 | EnableCodeIndexing: Yes 8 | UseSpacesForTab: Yes 9 | NumSpacesForTab: 2 10 | Encoding: UTF-8 11 | 12 | RnwWeave: Sweave 13 | LaTeX: pdfLaTeX 14 | 15 | AutoAppendNewline: Yes 16 | StripTrailingWhitespace: Yes 17 | 18 | BuildType: Package 19 | PackageUseDevtools: Yes 20 | PackageInstallArgs: --no-multiarch --with-keep.source 21 | --------------------------------------------------------------------------------