purrrlyr/0000755000176200001440000000000014220601322012143 5ustar liggesuserspurrrlyr/NAMESPACE0000644000176200001440000000051613766441225013406 0ustar liggesusers# Generated by roxygen2: do not edit by hand export("%>%") export(by_row) export(by_slice) export(dmap) export(dmap_at) export(dmap_if) export(invoke_rows) export(map_rows) export(slice_rows) export(unslice) importFrom(Rcpp,sourceCpp) importFrom(dplyr,group_data) importFrom(magrittr,"%>%") useDynLib(purrrlyr, .registration = TRUE) purrrlyr/LICENSE0000644000176200001440000010451313105124725013164 0ustar liggesusers GNU GENERAL PUBLIC LICENSE Version 3, 29 June 2007 Copyright (C) 2007 Free Software Foundation, Inc. Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble The GNU General Public License is a free, copyleft license for software and other kinds of works. The licenses for most software and other practical works are designed to take away your freedom to share and change the works. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change all versions of a program--to make sure it remains free software for all its users. We, the Free Software Foundation, use the GNU General Public License for most of our software; it applies also to any other work released this way by its authors. You can apply it to your programs, too. When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for them if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs, and that you know you can do these things. To protect your rights, we need to prevent others from denying you these rights or asking you to surrender the rights. Therefore, you have certain responsibilities if you distribute copies of the software, or if you modify it: responsibilities to respect the freedom of others. For example, if you distribute copies of such a program, whether gratis or for a fee, you must pass on to the recipients the same freedoms that you received. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights. Developers that use the GNU GPL protect your rights with two steps: (1) assert copyright on the software, and (2) offer you this License giving you legal permission to copy, distribute and/or modify it. For the developers' and authors' protection, the GPL clearly explains that there is no warranty for this free software. For both users' and authors' sake, the GPL requires that modified versions be marked as changed, so that their problems will not be attributed erroneously to authors of previous versions. Some devices are designed to deny users access to install or run modified versions of the software inside them, although the manufacturer can do so. This is fundamentally incompatible with the aim of protecting users' freedom to change the software. The systematic pattern of such abuse occurs in the area of products for individuals to use, which is precisely where it is most unacceptable. Therefore, we have designed this version of the GPL to prohibit the practice for those products. If such problems arise substantially in other domains, we stand ready to extend this provision to those domains in future versions of the GPL, as needed to protect the freedom of users. Finally, every program is threatened constantly by software patents. States should not allow patents to restrict development and use of software on general-purpose computers, but in those that do, we wish to avoid the special danger that patents applied to a free program could make it effectively proprietary. To prevent this, the GPL assures that patents cannot be used to render the program non-free. The precise terms and conditions for copying, distribution and modification follow. TERMS AND CONDITIONS 0. Definitions. "This License" refers to version 3 of the GNU General Public License. "Copyright" also means copyright-like laws that apply to other kinds of works, such as semiconductor masks. "The Program" refers to any copyrightable work licensed under this License. Each licensee is addressed as "you". "Licensees" and "recipients" may be individuals or organizations. To "modify" a work means to copy from or adapt all or part of the work in a fashion requiring copyright permission, other than the making of an exact copy. The resulting work is called a "modified version" of the earlier work or a work "based on" the earlier work. A "covered work" means either the unmodified Program or a work based on the Program. To "propagate" a work means to do anything with it that, without permission, would make you directly or secondarily liable for infringement under applicable copyright law, except executing it on a computer or modifying a private copy. Propagation includes copying, distribution (with or without modification), making available to the public, and in some countries other activities as well. To "convey" a work means any kind of propagation that enables other parties to make or receive copies. Mere interaction with a user through a computer network, with no transfer of a copy, is not conveying. An interactive user interface displays "Appropriate Legal Notices" to the extent that it includes a convenient and prominently visible feature that (1) displays an appropriate copyright notice, and (2) tells the user that there is no warranty for the work (except to the extent that warranties are provided), that licensees may convey the work under this License, and how to view a copy of this License. If the interface presents a list of user commands or options, such as a menu, a prominent item in the list meets this criterion. 1. Source Code. The "source code" for a work means the preferred form of the work for making modifications to it. "Object code" means any non-source form of a work. A "Standard Interface" means an interface that either is an official standard defined by a recognized standards body, or, in the case of interfaces specified for a particular programming language, one that is widely used among developers working in that language. The "System Libraries" of an executable work include anything, other than the work as a whole, that (a) is included in the normal form of packaging a Major Component, but which is not part of that Major Component, and (b) serves only to enable use of the work with that Major Component, or to implement a Standard Interface for which an implementation is available to the public in source code form. A "Major Component", in this context, means a major essential component (kernel, window system, and so on) of the specific operating system (if any) on which the executable work runs, or a compiler used to produce the work, or an object code interpreter used to run it. The "Corresponding Source" for a work in object code form means all the source code needed to generate, install, and (for an executable work) run the object code and to modify the work, including scripts to control those activities. However, it does not include the work's System Libraries, or general-purpose tools or generally available free programs which are used unmodified in performing those activities but which are not part of the work. For example, Corresponding Source includes interface definition files associated with source files for the work, and the source code for shared libraries and dynamically linked subprograms that the work is specifically designed to require, such as by intimate data communication or control flow between those subprograms and other parts of the work. The Corresponding Source need not include anything that users can regenerate automatically from other parts of the Corresponding Source. The Corresponding Source for a work in source code form is that same work. 2. Basic Permissions. All rights granted under this License are granted for the term of copyright on the Program, and are irrevocable provided the stated conditions are met. This License explicitly affirms your unlimited permission to run the unmodified Program. The output from running a covered work is covered by this License only if the output, given its content, constitutes a covered work. This License acknowledges your rights of fair use or other equivalent, as provided by copyright law. You may make, run and propagate covered works that you do not convey, without conditions so long as your license otherwise remains in force. You may convey covered works to others for the sole purpose of having them make modifications exclusively for you, or provide you with facilities for running those works, provided that you comply with the terms of this License in conveying all material for which you do not control copyright. Those thus making or running the covered works for you must do so exclusively on your behalf, under your direction and control, on terms that prohibit them from making any copies of your copyrighted material outside their relationship with you. Conveying under any other circumstances is permitted solely under the conditions stated below. Sublicensing is not allowed; section 10 makes it unnecessary. 3. Protecting Users' Legal Rights From Anti-Circumvention Law. No covered work shall be deemed part of an effective technological measure under any applicable law fulfilling obligations under article 11 of the WIPO copyright treaty adopted on 20 December 1996, or similar laws prohibiting or restricting circumvention of such measures. When you convey a covered work, you waive any legal power to forbid circumvention of technological measures to the extent such circumvention is effected by exercising rights under this License with respect to the covered work, and you disclaim any intention to limit operation or modification of the work as a means of enforcing, against the work's users, your or third parties' legal rights to forbid circumvention of technological measures. 4. Conveying Verbatim Copies. You may convey verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice; keep intact all notices stating that this License and any non-permissive terms added in accord with section 7 apply to the code; keep intact all notices of the absence of any warranty; and give all recipients a copy of this License along with the Program. You may charge any price or no price for each copy that you convey, and you may offer support or warranty protection for a fee. 5. Conveying Modified Source Versions. You may convey a work based on the Program, or the modifications to produce it from the Program, in the form of source code under the terms of section 4, provided that you also meet all of these conditions: a) The work must carry prominent notices stating that you modified it, and giving a relevant date. b) The work must carry prominent notices stating that it is released under this License and any conditions added under section 7. This requirement modifies the requirement in section 4 to "keep intact all notices". c) You must license the entire work, as a whole, under this License to anyone who comes into possession of a copy. This License will therefore apply, along with any applicable section 7 additional terms, to the whole of the work, and all its parts, regardless of how they are packaged. This License gives no permission to license the work in any other way, but it does not invalidate such permission if you have separately received it. d) If the work has interactive user interfaces, each must display Appropriate Legal Notices; however, if the Program has interactive interfaces that do not display Appropriate Legal Notices, your work need not make them do so. A compilation of a covered work with other separate and independent works, which are not by their nature extensions of the covered work, and which are not combined with it such as to form a larger program, in or on a volume of a storage or distribution medium, is called an "aggregate" if the compilation and its resulting copyright are not used to limit the access or legal rights of the compilation's users beyond what the individual works permit. Inclusion of a covered work in an aggregate does not cause this License to apply to the other parts of the aggregate. 6. Conveying Non-Source Forms. You may convey a covered work in object code form under the terms of sections 4 and 5, provided that you also convey the machine-readable Corresponding Source under the terms of this License, in one of these ways: a) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by the Corresponding Source fixed on a durable physical medium customarily used for software interchange. b) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by a written offer, valid for at least three years and valid for as long as you offer spare parts or customer support for that product model, to give anyone who possesses the object code either (1) a copy of the Corresponding Source for all the software in the product that is covered by this License, on a durable physical medium customarily used for software interchange, for a price no more than your reasonable cost of physically performing this conveying of source, or (2) access to copy the Corresponding Source from a network server at no charge. c) Convey individual copies of the object code with a copy of the written offer to provide the Corresponding Source. This alternative is allowed only occasionally and noncommercially, and only if you received the object code with such an offer, in accord with subsection 6b. d) Convey the object code by offering access from a designated place (gratis or for a charge), and offer equivalent access to the Corresponding Source in the same way through the same place at no further charge. You need not require recipients to copy the Corresponding Source along with the object code. If the place to copy the object code is a network server, the Corresponding Source may be on a different server (operated by you or a third party) that supports equivalent copying facilities, provided you maintain clear directions next to the object code saying where to find the Corresponding Source. Regardless of what server hosts the Corresponding Source, you remain obligated to ensure that it is available for as long as needed to satisfy these requirements. e) Convey the object code using peer-to-peer transmission, provided you inform other peers where the object code and Corresponding Source of the work are being offered to the general public at no charge under subsection 6d. A separable portion of the object code, whose source code is excluded from the Corresponding Source as a System Library, need not be included in conveying the object code work. A "User Product" is either (1) a "consumer product", which means any tangible personal property which is normally used for personal, family, or household purposes, or (2) anything designed or sold for incorporation into a dwelling. In determining whether a product is a consumer product, doubtful cases shall be resolved in favor of coverage. For a particular product received by a particular user, "normally used" refers to a typical or common use of that class of product, regardless of the status of the particular user or of the way in which the particular user actually uses, or expects or is expected to use, the product. A product is a consumer product regardless of whether the product has substantial commercial, industrial or non-consumer uses, unless such uses represent the only significant mode of use of the product. "Installation Information" for a User Product means any methods, procedures, authorization keys, or other information required to install and execute modified versions of a covered work in that User Product from a modified version of its Corresponding Source. The information must suffice to ensure that the continued functioning of the modified object code is in no case prevented or interfered with solely because modification has been made. If you convey an object code work under this section in, or with, or specifically for use in, a User Product, and the conveying occurs as part of a transaction in which the right of possession and use of the User Product is transferred to the recipient in perpetuity or for a fixed term (regardless of how the transaction is characterized), the Corresponding Source conveyed under this section must be accompanied by the Installation Information. But this requirement does not apply if neither you nor any third party retains the ability to install modified object code on the User Product (for example, the work has been installed in ROM). The requirement to provide Installation Information does not include a requirement to continue to provide support service, warranty, or updates for a work that has been modified or installed by the recipient, or for the User Product in which it has been modified or installed. Access to a network may be denied when the modification itself materially and adversely affects the operation of the network or violates the rules and protocols for communication across the network. Corresponding Source conveyed, and Installation Information provided, in accord with this section must be in a format that is publicly documented (and with an implementation available to the public in source code form), and must require no special password or key for unpacking, reading or copying. 7. Additional Terms. "Additional permissions" are terms that supplement the terms of this License by making exceptions from one or more of its conditions. Additional permissions that are applicable to the entire Program shall be treated as though they were included in this License, to the extent that they are valid under applicable law. If additional permissions apply only to part of the Program, that part may be used separately under those permissions, but the entire Program remains governed by this License without regard to the additional permissions. When you convey a copy of a covered work, you may at your option remove any additional permissions from that copy, or from any part of it. (Additional permissions may be written to require their own removal in certain cases when you modify the work.) You may place additional permissions on material, added by you to a covered work, for which you have or can give appropriate copyright permission. Notwithstanding any other provision of this License, for material you add to a covered work, you may (if authorized by the copyright holders of that material) supplement the terms of this License with terms: a) Disclaiming warranty or limiting liability differently from the terms of sections 15 and 16 of this License; or b) Requiring preservation of specified reasonable legal notices or author attributions in that material or in the Appropriate Legal Notices displayed by works containing it; or c) Prohibiting misrepresentation of the origin of that material, or requiring that modified versions of such material be marked in reasonable ways as different from the original version; or d) Limiting the use for publicity purposes of names of licensors or authors of the material; or e) Declining to grant rights under trademark law for use of some trade names, trademarks, or service marks; or f) Requiring indemnification of licensors and authors of that material by anyone who conveys the material (or modified versions of it) with contractual assumptions of liability to the recipient, for any liability that these contractual assumptions directly impose on those licensors and authors. All other non-permissive additional terms are considered "further restrictions" within the meaning of section 10. If the Program as you received it, or any part of it, contains a notice stating that it is governed by this License along with a term that is a further restriction, you may remove that term. If a license document contains a further restriction but permits relicensing or conveying under this License, you may add to a covered work material governed by the terms of that license document, provided that the further restriction does not survive such relicensing or conveying. If you add terms to a covered work in accord with this section, you must place, in the relevant source files, a statement of the additional terms that apply to those files, or a notice indicating where to find the applicable terms. Additional terms, permissive or non-permissive, may be stated in the form of a separately written license, or stated as exceptions; the above requirements apply either way. 8. Termination. You may not propagate or modify a covered work except as expressly provided under this License. Any attempt otherwise to propagate or modify it is void, and will automatically terminate your rights under this License (including any patent licenses granted under the third paragraph of section 11). However, if you cease all violation of this License, then your license from a particular copyright holder is reinstated (a) provisionally, unless and until the copyright holder explicitly and finally terminates your license, and (b) permanently, if the copyright holder fails to notify you of the violation by some reasonable means prior to 60 days after the cessation. Moreover, your license from a particular copyright holder is reinstated permanently if the copyright holder notifies you of the violation by some reasonable means, this is the first time you have received notice of violation of this License (for any work) from that copyright holder, and you cure the violation prior to 30 days after your receipt of the notice. Termination of your rights under this section does not terminate the licenses of parties who have received copies or rights from you under this License. If your rights have been terminated and not permanently reinstated, you do not qualify to receive new licenses for the same material under section 10. 9. Acceptance Not Required for Having Copies. You are not required to accept this License in order to receive or run a copy of the Program. Ancillary propagation of a covered work occurring solely as a consequence of using peer-to-peer transmission to receive a copy likewise does not require acceptance. However, nothing other than this License grants you permission to propagate or modify any covered work. These actions infringe copyright if you do not accept this License. Therefore, by modifying or propagating a covered work, you indicate your acceptance of this License to do so. 10. Automatic Licensing of Downstream Recipients. Each time you convey a covered work, the recipient automatically receives a license from the original licensors, to run, modify and propagate that work, subject to this License. You are not responsible for enforcing compliance by third parties with this License. An "entity transaction" is a transaction transferring control of an organization, or substantially all assets of one, or subdividing an organization, or merging organizations. If propagation of a covered work results from an entity transaction, each party to that transaction who receives a copy of the work also receives whatever licenses to the work the party's predecessor in interest had or could give under the previous paragraph, plus a right to possession of the Corresponding Source of the work from the predecessor in interest, if the predecessor has it or can get it with reasonable efforts. You may not impose any further restrictions on the exercise of the rights granted or affirmed under this License. For example, you may not impose a license fee, royalty, or other charge for exercise of rights granted under this License, and you may not initiate litigation (including a cross-claim or counterclaim in a lawsuit) alleging that any patent claim is infringed by making, using, selling, offering for sale, or importing the Program or any portion of it. 11. Patents. A "contributor" is a copyright holder who authorizes use under this License of the Program or a work on which the Program is based. The work thus licensed is called the contributor's "contributor version". A contributor's "essential patent claims" are all patent claims owned or controlled by the contributor, whether already acquired or hereafter acquired, that would be infringed by some manner, permitted by this License, of making, using, or selling its contributor version, but do not include claims that would be infringed only as a consequence of further modification of the contributor version. For purposes of this definition, "control" includes the right to grant patent sublicenses in a manner consistent with the requirements of this License. Each contributor grants you a non-exclusive, worldwide, royalty-free patent license under the contributor's essential patent claims, to make, use, sell, offer for sale, import and otherwise run, modify and propagate the contents of its contributor version. In the following three paragraphs, a "patent license" is any express agreement or commitment, however denominated, not to enforce a patent (such as an express permission to practice a patent or covenant not to sue for patent infringement). To "grant" such a patent license to a party means to make such an agreement or commitment not to enforce a patent against the party. If you convey a covered work, knowingly relying on a patent license, and the Corresponding Source of the work is not available for anyone to copy, free of charge and under the terms of this License, through a publicly available network server or other readily accessible means, then you must either (1) cause the Corresponding Source to be so available, or (2) arrange to deprive yourself of the benefit of the patent license for this particular work, or (3) arrange, in a manner consistent with the requirements of this License, to extend the patent license to downstream recipients. "Knowingly relying" means you have actual knowledge that, but for the patent license, your conveying the covered work in a country, or your recipient's use of the covered work in a country, would infringe one or more identifiable patents in that country that you have reason to believe are valid. If, pursuant to or in connection with a single transaction or arrangement, you convey, or propagate by procuring conveyance of, a covered work, and grant a patent license to some of the parties receiving the covered work authorizing them to use, propagate, modify or convey a specific copy of the covered work, then the patent license you grant is automatically extended to all recipients of the covered work and works based on it. A patent license is "discriminatory" if it does not include within the scope of its coverage, prohibits the exercise of, or is conditioned on the non-exercise of one or more of the rights that are specifically granted under this License. You may not convey a covered work if you are a party to an arrangement with a third party that is in the business of distributing software, under which you make payment to the third party based on the extent of your activity of conveying the work, and under which the third party grants, to any of the parties who would receive the covered work from you, a discriminatory patent license (a) in connection with copies of the covered work conveyed by you (or copies made from those copies), or (b) primarily for and in connection with specific products or compilations that contain the covered work, unless you entered into that arrangement, or that patent license was granted, prior to 28 March 2007. Nothing in this License shall be construed as excluding or limiting any implied license or other defenses to infringement that may otherwise be available to you under applicable patent law. 12. No Surrender of Others' Freedom. If conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot convey a covered work so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not convey it at all. For example, if you agree to terms that obligate you to collect a royalty for further conveying from those to whom you convey the Program, the only way you could satisfy both those terms and this License would be to refrain entirely from conveying the Program. 13. Use with the GNU Affero General Public License. Notwithstanding any other provision of this License, you have permission to link or combine any covered work with a work licensed under version 3 of the GNU Affero General Public License into a single combined work, and to convey the resulting work. The terms of this License will continue to apply to the part which is the covered work, but the special requirements of the GNU Affero General Public License, section 13, concerning interaction through a network will apply to the combination as such. 14. Revised Versions of this License. The Free Software Foundation may publish revised and/or new versions of the GNU General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Program specifies that a certain numbered version of the GNU General Public License "or any later version" applies to it, you have the option of following the terms and conditions either of that numbered version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of the GNU General Public License, you may choose any version ever published by the Free Software Foundation. If the Program specifies that a proxy can decide which future versions of the GNU General Public License can be used, that proxy's public statement of acceptance of a version permanently authorizes you to choose that version for the Program. Later license versions may give you additional or different permissions. However, no additional obligations are imposed on any author or copyright holder as a result of your choosing to follow a later version. 15. Disclaimer of Warranty. THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 16. Limitation of Liability. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. 17. Interpretation of Sections 15 and 16. If the disclaimer of warranty and limitation of liability provided above cannot be given local legal effect according to their terms, reviewing courts shall apply local law that most closely approximates an absolute waiver of all civil liability in connection with the Program, unless a warranty or assumption of liability accompanies a copy of the Program in return for a fee. END OF TERMS AND CONDITIONS How to Apply These Terms to Your New Programs If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms. To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively state the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. Copyright (C) This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see . Also add information on how to contact you by electronic and paper mail. If the program does terminal interaction, make it output a short notice like this when it starts in an interactive mode: Copyright (C) This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details. The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, your program's commands might be different; for a GUI interface, you would use an "about box". You should also get your employer (if you work as a programmer) or school, if any, to sign a "copyright disclaimer" for the program, if necessary. For more information on this, and how to apply and follow the GNU GPL, see . The GNU General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Lesser General Public License instead of this License. But first, please read . purrrlyr/README.md0000644000176200001440000000176114220550353013436 0ustar liggesusers# purrrlyr [![Lifecycle: superseded](https://img.shields.io/badge/lifecycle-superseded-blue.svg)](https://lifecycle.r-lib.org/articles/stages.html) [![CRAN_Status_Badge](http://www.r-pkg.org/badges/version/purrrlyr)](https://cran.r-project.org/package=purrrlyr) [![Codecov test coverage](https://codecov.io/gh/hadley/purrrlyr/branch/master/graph/badge.svg)](https://app.codecov.io/gh/hadley/purrrlyr?branch=master) [![R-CMD-check](https://github.com/hadley/purrrlyr/actions/workflows/R-CMD-check.yaml/badge.svg)](https://github.com/hadley/purrrlyr/actions/workflows/R-CMD-check.yaml) purrrlyr contains some functions that lie at the intersection of purrr and dplyr. They have been removed from purrr in order to make the package lighter and because they have been replaced by other solutions in the tidyverse. Please see Jenny Brian's [webinar on row-oriented workflows](https://github.com/jennybc/row-oriented-workflows#readme) for some alternative approaches. purrrlyr/man/0000755000176200001440000000000014024413147012726 5ustar liggesuserspurrrlyr/man/by_slice.Rd0000644000176200001440000000605013766424232015020 0ustar liggesusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/rows.R \name{by_slice} \alias{by_slice} \title{Apply a function to slices of a data frame} \usage{ by_slice( .d, ..f, ..., .collate = c("list", "rows", "cols"), .to = ".out", .labels = TRUE ) } \arguments{ \item{.d}{A sliced data frame.} \item{..f}{A function to apply to each slice. If \code{..f} does not return a data frame or an atomic vector, a list-column is created under the name \code{.out}. If it returns a data frame, it should have the same number of rows within groups and the same number of columns between groups.} \item{...}{Further arguments passed to \code{..f}.} \item{.collate}{If "list", the results are returned as a list- column. Alternatively, if the results are data frames or atomic vectors, you can collate on "cols" or on "rows". Column collation require vector of equal length or data frames with same number of rows.} \item{.to}{Name of output column.} \item{.labels}{If \code{TRUE}, the returned data frame is prepended with the labels of the slices (the columns in \code{.d} used to define the slices). They are recycled to match the output size in each slice if necessary.} } \value{ A data frame. } \description{ \code{by_slice()} applies \code{..f} on each group of a data frame. Groups should be set with \code{slice_rows()} or \code{\link[dplyr:group_by]{dplyr::group_by()}}. } \details{ \code{by_slice()} provides equivalent functionality to dplyr's \code{\link[dplyr:do]{dplyr::do()}} function. In combination with \code{map()}, \code{by_slice()} is equivalent to \code{\link[dplyr:summarise_each]{dplyr::summarise_each()}} and \code{\link[dplyr:summarise_each]{dplyr::mutate_each()}}. The distinction between mutating and summarising operations is not as important as in dplyr because we do not act on the columns separately. The only constraint is that the mapped function must return the same number of rows for each variable mapped on. } \examples{ # Here we fit a regression model inside each slice defined by the # unique values of the column "cyl". The fitted models are returned # in a list-column. mtcars \%>\% slice_rows("cyl") \%>\% by_slice(purrr::partial(lm, mpg ~ disp)) # by_slice() is especially useful in combination with map(). # To modify the contents of a data frame, use rows collation. Note # that unlike dplyr, Mutating and summarising operations can be # used indistinctly. # Mutating operation: df <- mtcars \%>\% slice_rows(c("cyl", "am")) df \%>\% by_slice(dmap, ~ .x / sum(.x), .collate = "rows") # Summarising operation: df \%>\% by_slice(dmap, mean, .collate = "rows") # Note that mapping columns within slices is best handled by dmap(): df \%>\% dmap(~ .x / sum(.x)) df \%>\% dmap(mean) # If you don't need the slicing variables as identifiers, switch # .labels to FALSE: mtcars \%>\% slice_rows("cyl") \%>\% by_slice(purrr::partial(lm, mpg ~ disp), .labels = FALSE) \%>\% purrr::flatten() \%>\% purrr::map(coef) } \seealso{ \code{\link[=by_row]{by_row()}}, \code{\link[=slice_rows]{slice_rows()}}, \code{\link[=dmap]{dmap()}} } purrrlyr/man/by_row.Rd0000644000176200001440000000735213652207662014536 0ustar liggesusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/rows.R \name{by_row} \alias{by_row} \alias{invoke_rows} \alias{map_rows} \title{Apply a function to each row of a data frame} \usage{ by_row( .d, ..f, ..., .collate = c("list", "rows", "cols"), .to = ".out", .labels = TRUE ) invoke_rows( .f, .d, ..., .collate = c("list", "rows", "cols"), .to = ".out", .labels = TRUE ) } \arguments{ \item{.d}{A data frame.} \item{...}{Further arguments passed to \code{..f}.} \item{.collate}{If "list", the results are returned as a list- column. Alternatively, if the results are data frames or atomic vectors, you can collate on "cols" or on "rows". Column collation require vector of equal length or data frames with same number of rows.} \item{.to}{Name of output column.} \item{.labels}{If \code{TRUE}, the returned data frame is prepended with the labels of the slices (the columns in \code{.d} used to define the slices). They are recycled to match the output size in each slice if necessary.} \item{.f, ..f}{A function to apply to each row. If \code{..f} does not return a data frame or an atomic vector, a list-column is created under the name \code{.out}. If it returns a data frame, it should have the same number of rows within groups and the same number of columns between groups.} } \value{ A data frame. } \description{ \code{by_row()} and \code{invoke_rows()} apply \code{..f} to each row of \code{.d}. If \code{..f}'s output is not a data frame nor an atomic vector, a list-column is created. In all cases, \code{by_row()} and \code{invoke_rows()} create a data frame in tidy format. } \details{ By default, the whole row is appended to the result to serve as identifier (set \code{.labels} to \code{FALSE} to prevent this). In addition, if \code{..f} returns a multi-rows data frame or a non-scalar atomic vector, a \code{.row} column is appended to identify the row number in the original data frame. \code{invoke_rows()} is intended to provide a version of \code{pmap()} for data frames. Its default collation method is \code{"cols"}, which makes it equivalent to \code{mdply()} from the plyr package. Note that \code{invoke_rows()} follows the signature pattern of the \code{invoke} family of functions and takes \code{.f} as its first argument. The distinction between \code{by_row()} and \code{invoke_rows()} is that the former passes a data frame to \code{..f} while the latter maps the columns to its function call. This is essentially like using \code{\link[=invoke]{invoke()}} with each row. Another way to view this is that \code{invoke_rows()} is equivalent to using \code{by_row()} with a function lifted to accept dots (see \code{\link[=lift]{lift()}}). } \examples{ # ..f should be able to work with a list or a data frame. As it # happens, sum() handles data frame so the following works: mtcars \%>\% by_row(sum) # Other functions such as mean() may need to be adjusted with one # of the lift_xy() helpers: mtcars \%>\% by_row(purrr::lift_vl(mean)) # To run a function with invoke_rows(), make sure it is variadic (that # it accepts dots) or that .f's signature is compatible with the # column names mtcars \%>\% invoke_rows(.f = sum) mtcars \%>\% invoke_rows(.f = purrr::lift_vd(mean)) # invoke_rows() with cols collation is equivalent to plyr::mdply() p <- expand.grid(mean = 1:5, sd = seq(0, 1, length = 10)) p \%>\% invoke_rows(.f = rnorm, n = 5, .collate = "cols") \dontrun{ p \%>\% plyr::mdply(rnorm, n = 5) \%>\% dplyr::tbl_df() } # To integrate the result as part of the data frame, use rows or # cols collation: mtcars[1:2] \%>\% by_row(function(x) 1:5) mtcars[1:2] \%>\% by_row(function(x) 1:5, .collate = "rows") mtcars[1:2] \%>\% by_row(function(x) 1:5, .collate = "cols") } \seealso{ \code{\link[=by_slice]{by_slice()}} } purrrlyr/man/pipe.Rd0000644000176200001440000000032013105124725014145 0ustar liggesusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/utils.R \name{\%>\%} \alias{\%>\%} \title{Pipe operator} \usage{ lhs \%>\% rhs } \description{ Pipe operator } \keyword{internal} purrrlyr/man/slice_rows.Rd0000644000176200001440000000153213105124725015367 0ustar liggesusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/rows.R \name{slice_rows} \alias{slice_rows} \alias{unslice} \title{Slice a data frame into groups of rows} \usage{ slice_rows(.d, .cols = NULL) unslice(.d) } \arguments{ \item{.d}{A data frame to slice or unslice.} \item{.cols}{A character vector of column names or a numeric vector of column positions. If \code{NULL}, the slicing attributes are removed.} } \value{ A sliced or unsliced data frame. } \description{ \code{slice_rows()} is equivalent to dplyr's \code{\link[dplyr:group_by]{dplyr::group_by()}} command but it takes a vector of column names or positions instead of capturing column names with special evaluation. \code{unslice()} removes the slicing attributes. } \seealso{ \code{\link[=by_slice]{by_slice()}} and \code{\link[dplyr:group_by]{dplyr::group_by()}} } purrrlyr/man/dmap.Rd0000644000176200001440000000477713431472164014162 0ustar liggesusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/dmap.R \name{dmap} \alias{dmap} \alias{dmap_at} \alias{dmap_if} \title{Map over the columns of a data frame} \usage{ dmap(.d, .f, ...) dmap_at(.d, .at, .f, ...) dmap_if(.d, .p, .f, ...) } \arguments{ \item{.d}{A data frame.} \item{.f}{A function, formula, or vector (not necessarily atomic). If a \strong{function}, it is used as is. If a \strong{formula}, e.g. \code{~ .x + 2}, it is converted to a function. There are three ways to refer to the arguments: \itemize{ \item For a single argument function, use \code{.} \item For a two argument function, use \code{.x} and \code{.y} \item For more arguments, use \code{..1}, \code{..2}, \code{..3} etc } This syntax allows you to create very compact anonymous functions. If \strong{character vector}, \strong{numeric vector}, or \strong{list}, it is converted to an extractor function. Character vectors index by name and numeric vectors index by position; use a list to index by position and name at different levels. If a component is not present, the value of \code{.default} will be returned.} \item{...}{Additional arguments passed on to the mapped function.} \item{.at}{A character vector of names, positive numeric vector of positions to include, or a negative numeric vector of positions to exlude. Only those elements corresponding to \code{.at} will be modified. If the \code{tidyselect} package is installed, you can use \code{vars()} and the \code{tidyselect} helpers to select elements.} \item{.p}{A single predicate function, a formula describing such a predicate function, or a logical vector of the same length as \code{.x}. Alternatively, if the elements of \code{.x} are themselves lists of objects, a string indicating the name of a logical element in the inner lists. Only those elements where \code{.p} evaluates to \code{TRUE} will be modified.} } \description{ \code{dmap()} is just like \code{\link[purrr:map]{purrr::map()}} but always returns a data frame. In addition, it handles grouped or sliced data frames. } \details{ \code{dmap_at()} and \code{dmap_if()} recycle length 1 vectors to the group sizes. } \examples{ # dmap() always returns a data frame: dmap(mtcars, summary) # dmap() also supports sliced data frames: sliced_df <- mtcars[1:5] \%>\% slice_rows("cyl") sliced_df \%>\% dmap(mean) sliced_df \%>\% dmap(~ .x / max(.x)) # This is equivalent to the combination of by_slice() and dmap() # with 'rows' collation of results: sliced_df \%>\% by_slice(dmap, mean, .collate = "rows") } purrrlyr/DESCRIPTION0000644000176200001440000000214114220601322013647 0ustar liggesusersPackage: purrrlyr Title: Tools at the Intersection of 'purrr' and 'dplyr' Version: 0.0.8 Authors@R: c(person(given = "Lionel", family = "Henry", role = c("aut", "cre"), email = "lionel@rstudio.com"), person(given = "Hadley", family = "Wickham", role = "ctb", email = "hadley@rstudio.com"), person(given = "RStudio", role = "cph")) Description: Some functions at the intersection of 'dplyr' and 'purrr' that formerly lived in 'purrr'. License: GPL-3 | file LICENSE URL: https://github.com/hadley/purrrlyr BugReports: https://github.com/hadley/purrrlyr/issues Imports: dplyr (>= 0.8.0), magrittr (>= 1.5), purrr (>= 0.2.2), Rcpp Suggests: covr, testthat (>= 3.0.0) LinkingTo: Rcpp SystemRequirements: C++11 Encoding: UTF-8 RoxygenNote: 7.1.1 Config/testthat/edition: 3 NeedsCompilation: yes Packaged: 2022-03-29 09:51:57 UTC; lionel Author: Lionel Henry [aut, cre], Hadley Wickham [ctb], RStudio [cph] Maintainer: Lionel Henry Repository: CRAN Date/Publication: 2022-03-29 13:00:02 UTC purrrlyr/tests/0000755000176200001440000000000014024273171013316 5ustar liggesuserspurrrlyr/tests/testthat/0000755000176200001440000000000014220601322015145 5ustar liggesuserspurrrlyr/tests/testthat/test-dmap.R0000644000176200001440000000216013766427473017220 0ustar liggesuserstest_that("dmap() returns a data frame", { expect_s3_class(dmap(mtcars, mean), "data.frame") }) test_that("dmap() works with sliced data frames", { df <- slice_rows(mtcars, "cyl") actual <- dmap(df, mean) expected <- by_slice(df, dmap, mean, .collate = "rows") expect_equal(actual, expected) }) test_that("dmap() works with no columns to map", { res <- mtcars["cyl"] %>% slice_rows("cyl") %>% dmap(mean) expect_equal(res, dplyr::group_by(mtcars["cyl"], cyl)) }) test_that("dmap() recycles only vectors of length 1", { expect_equal(dmap_at(mtcars, "cyl", mean)$cyl, rep(mean(mtcars$cyl), nrow(mtcars))) expect_error(dmap_at(mtcars, c("cyl", "am"), ~1:2), "only recycles") }) test_that("conditional sliced mapping recycles within groups", { df <- mtcars %>% slice_rows(c("vs", "am")) expected_df <- by_slice(df, dmap, mean, .collate = "rows") res_at <- dmap_at(df, c("disp", "drat"), mean) res_if <- dmap_if(df, ~ .x[[1]] == 160, mean) expected <- purrr::map2(expected_df$disp, group_sizes(df), rep) %>% purrr::flatten_dbl() expect_equal(res_at$disp, expected) expect_equal(res_if$disp, expected) }) purrrlyr/tests/testthat/test-rows.R0000644000176200001440000002037713766426674017305 0ustar liggesuserstest_that("output column is named according to .to", { output1 <- mtcars %>% slice_rows("cyl") %>% by_slice(~ list(NULL), .to = "my_col", .labels = FALSE) output2 <- mtcars %>% by_row(~ list(NULL), .to = "my_col", .labels = FALSE) output3 <- mtcars %>% invoke_rows(.f = function(...) list(NULL), .collate = "list", .to = "my_col", .labels = FALSE) expect_equal(names(output1), "my_col") expect_equal(names(output2), "my_col") expect_equal(names(output3), "my_col") }) test_that("empty", { rows_collation <- invoke_rows(empty, mtcars[1:2], .collate = "rows") cols_collation <- invoke_rows(empty, mtcars[1:2], .collate = "cols") list_collation <- invoke_rows(empty, mtcars[1:2], .collate = "list") expect_equal(rows_collation$.out, numeric(0)) expect_equal(cols_collation$.out, numeric(0)) expect_equal(list_collation$.out, purrr::rerun(32, numeric(0))) expect_equal(dim(rows_collation), c(0, 3)) expect_equal(dim(cols_collation), c(0, 3)) expect_equal(dim(list_collation), c(32, 3)) }) test_that("all nulls fail, except with list-collation", { expect_error(invoke_rows(all_nulls, mtcars[1:2], .collate = "rows")) expect_error(invoke_rows(all_nulls, mtcars[1:2], .collate = "cols")) list_collation <- invoke_rows(all_nulls, mtcars[1:2], .collate = "list") expect_equal(list_collation$.out, vector("list", 32)) expect_equal(dim(list_collation), c(32, 3)) }) test_that("scalars", { rows_collation <- invoke_rows(scalars, mtcars[1:2], .collate = "rows") cols_collation <- invoke_rows(scalars, mtcars[1:2], .collate = "cols") list_collation <- invoke_rows(scalars, mtcars[1:2], .collate = "list") out <- paste("a", mtcars$mpg) expect_equal(rows_collation$.out, out) expect_equal(cols_collation$.out, out) expect_equal(list_collation$.out, as.list(out)) expect_equal(dim(rows_collation), c(32, 3)) expect_equal(dim(cols_collation), c(32, 3)) expect_equal(dim(list_collation), c(32, 3)) }) test_that("scalars with some nulls", { rows_collation <- invoke_rows(scalar_nulls, mtcars[1:2], .collate = "rows") cols_collation <- invoke_rows(scalar_nulls, mtcars[1:2], .collate = "cols") list_collation <- invoke_rows(scalar_nulls, mtcars[1:2], .collate = "list") expect_equal(rows_collation$.out, rep(1, 16)) expect_equal(cols_collation$.out, rep(1, 16)) expect_equal(list_collation$.out, rep(list(1L, NULL), 16)) expect_equal(dim(rows_collation), c(16, 3)) expect_equal(dim(cols_collation), c(16, 3)) expect_equal(dim(list_collation), c(32, 3)) # Make sure properties are well inferred when first result is NULL rows_collation <- invoke_rows(scalar_first_nulls, mtcars[1:2], .collate = "rows") expect_equal(rows_collation$.out, rep(1, 16)) }) test_that("labels are correctly subsetted", { rows_collation <- invoke_rows(scalar_first_nulls, mtcars[1:2], .collate = "rows") expect_equal(rows_collation[1:2], dplyr::as_tibble(mtcars[seq(2, 32, 2), 1:2])) }) test_that("vectors", { rows_collation <- invoke_rows(vectors, mtcars[1:2], .collate = "rows") cols_collation <- invoke_rows(vectors, mtcars[1:2], .collate = "cols") list_collation <- invoke_rows(vectors, mtcars[1:2], .collate = "list") data <- dplyr::rowwise(mtcars[1:2]) out <- dplyr::do(data, .out = paste(c("a", "b"), c(.$mpg, .$cyl)))[[1]] expect_equal(rows_collation$.row, rep(1:32, each = 2)) expect_equal(rows_collation$.out, unlist(out)) expect_equal(cols_collation$.out1, paste("a", mtcars$mpg)) expect_equal(cols_collation$.out2, paste("b", mtcars$cyl)) expect_equal(list_collation$.out, out) expect_equal(dim(rows_collation), c(64, 4)) expect_equal(dim(cols_collation), c(32, 4)) expect_equal(dim(list_collation), c(32, 3)) }) test_that("data frames", { rows_collation <- invoke_rows(dataframes, mtcars[1:2], .collate = "rows") cols_collation <- invoke_rows(dataframes, mtcars[1:2], .collate = "cols") list_collation <- invoke_rows(dataframes, mtcars[1:2], .collate = "list") expect_equal(rows_collation$.row, rep(1:32, each = 3)) expect_equal(rows_collation[4:5], dplyr::as_tibble(dplyr::bind_rows(purrr::rerun(32, df)))) expect_equal(cols_collation[[3]], rep(df[[1]][1], 32)) expect_equal(cols_collation[[8]], rep(df[[2]][3], 32)) expect_equal(list_collation$.out, purrr::rerun(32, df)) expect_equal(dim(rows_collation), c(96, 5)) expect_equal(dim(cols_collation), c(32, 8)) expect_equal(dim(list_collation), c(32, 3)) }) test_that("data frames with some nulls/empty", { rows_collation <- invoke_rows(dataframes_nulls, mtcars[1:2], .collate = "rows") cols_collation <- invoke_rows(dataframes_nulls, mtcars[1:2], .collate = "cols") list_collation <- invoke_rows(dataframes_nulls, mtcars[1:2], .collate = "list") expect_equal(rows_collation[4:5], dplyr::as_tibble(dplyr::bind_rows(purrr::rerun(16, df)))) expect_equal(list_collation$.out, rep(list(df, NULL), 16)) expect_equal(dim(rows_collation), c(48, 5)) expect_equal(dim(cols_collation), c(16, 8)) expect_equal(dim(list_collation), c(32, 3)) }) test_that("empty data frames", { rows_collation_by_row <- invoke_rows(empty_dataframes, mtcars[1:2], .collate = "rows") rows_collation_by_slice <- by_slice(grouped, empty_dataframes, .collate = "rows") expect_equal(rows_collation_by_row[4:5], dplyr::as_tibble(df[0, ])) expect_equal(rows_collation_by_slice[2:3], dplyr::as_tibble(df[0, ])) expect_equal(dim(rows_collation_by_row), c(0, 5)) expect_equal(dim(rows_collation_by_slice), c(0, 3)) }) test_that("some empty data frames", { rows_collation_by_row <- invoke_rows(some_empty_dataframes, mtcars[1:2], .collate = "rows") rows_collation_by_slice <- by_slice(grouped, some_empty_dataframes, .collate = "rows") expect_equal(rows_collation_by_row[4:5], dplyr::as_tibble(dplyr::bind_rows(purrr::rerun(16, df)))) expect_equal(rows_collation_by_slice[2:3], dplyr::as_tibble(dplyr::bind_rows(purrr::rerun(2, df)))) expect_equal(dim(rows_collation_by_row), c(48, 5)) expect_equal(dim(rows_collation_by_slice), c(6, 3)) }) test_that("unconsistent data frames fail", { expect_error(invoke_rows(unconsistent_names, mtcars[1:2], .collate = "rows"), "consistent names") expect_error(invoke_rows(unconsistent_types, mtcars[1:2], .collate = "rows"), "must return either data frames or vectors") }) test_that("objects", { list_collation <- invoke_rows(test_objects, mtcars[1:2], .collate = "list") expect_equal( list_collation$.out, rep(list(function() {}), 32), ignore_function_env = TRUE ) expect_equal(dim(list_collation), c(32, 3)) expect_error(invoke_rows(test_objects, mtcars[1:2], .collate = "rows")) expect_error(invoke_rows(test_objects, mtcars[1:2], .collate = "cols")) }) test_that("collation of ragged objects on cols fails", { expect_error(invoke_rows(ragged_dataframes, mtcars[1:2], .collate = "cols")) expect_error(invoke_rows(ragged_vectors, mtcars[1:2], .collate = "cols")) }) test_that("by_slice() works with slicers of different types", { df1 <- slice_rows(mtcars, "cyl") df2 <- dmap_at(mtcars, "cyl", as.character) %>% slice_rows("cyl") out1 <- by_slice(df1, purrr::map, mean) out2 <- by_slice(df2, purrr::map, mean) expect_identical(out1[-1], out2[-1]) expect_equal(typeof(out1$cyl), "double") expect_equal(typeof(out2$cyl), "character") }) test_that("by_slice() does not create .row column", { data <- slice_rows(mtcars[1:2], "cyl") rows_vectors <- by_slice(data, function(x) 1:3, .collate = "rows") expect_equal(dim(rows_vectors), c(9, 2)) expect_equal(names(rows_vectors), c("cyl", ".out")) rows_dfs <- by_slice(data, function(x) df, .collate = "rows") expect_equal(dim(rows_dfs), c(9, 3)) expect_equal(names(rows_dfs), c("cyl", "wt", "qsec")) }) test_that("by_slice() fails with ungrouped data frames", { expect_error(by_slice(mtcars, list)) }) test_that("by_row() creates indices with c++ style indexing", { out <- mtcars[1:5, 1:2] %>% by_row(~ .$cyl[1]) expect_equal(out$.out[[5]], 8) }) test_that("error is thrown when no columns to map", { expect_error(mtcars["cyl"] %>% slice_rows("cyl") %>% by_slice(list), "empty") expect_error(dplyr::tibble() %>% invoke_rows(.f = c), "empty") expect_error(dplyr::tibble() %>% by_row(c), "empty") }) test_that("grouping list-columns are copied (#9)", { df <- dplyr::tibble(x = as.list(1:2)) exp <- dplyr::tibble(x = list(1L, 2L), .out = list(NA, NA)) expect_identical(by_row(df, ~NA), exp) }) purrrlyr/tests/testthat/helper-rows.R0000644000176200001440000000213713766426062017566 0ustar liggesusers df <- mtcars[1:3, c("wt", "qsec")] df[[2]] <- as.character(df[[2]]) suppressWarnings(grouped <- slice_rows(mtcars[1:2], "cyl")) gen_alternatives <- function(first, alt) { prev_alt <- TRUE function(...) { if (prev_alt) { out <- first } else { out <- alt } prev_alt <<- !prev_alt out } } all_nulls <- function(...) NULL scalars <- function(...) paste("a", ..1) empty <- function(...) numeric(0) vectors <- function(...) paste(letters[1:2], c(...)) dataframes <- function(...) df empty_dataframes <- function(...) df[0, ] test_objects <- function(...) function() {} scalar_nulls <- gen_alternatives(1L, NULL) scalar_first_nulls <- gen_alternatives(NULL, 1L) scalar_first_nulls <- gen_alternatives(NULL, 1L) dataframes_nulls <- gen_alternatives(df, NULL) some_empty_dataframes <- gen_alternatives(df, df[0, ]) unconsistent_names <- gen_alternatives(df, purrr::set_names(df, 1:2)) unconsistent_types <- gen_alternatives(df, purrr::map(df, as.character)) ragged_dataframes <- gen_alternatives(df, rbind(df, df)) ragged_vectors <- gen_alternatives(letters[1:2], rep(letters[1:2], 2)) purrrlyr/tests/testthat.R0000644000176200001440000000007413105124725015301 0ustar liggesuserslibrary(testthat) library(purrrlyr) test_check("purrrlyr") purrrlyr/src/0000755000176200001440000000000014220553275012747 5ustar liggesuserspurrrlyr/src/map.h0000644000176200001440000000027313373227161013677 0ustar liggesusers#ifndef MAP_H #define MAP_H extern "C" { SEXP map_impl(SEXP env, SEXP x_name_, SEXP f_name_, SEXP type_); SEXP pmap_impl(SEXP env, SEXP l_name_, SEXP f_name_, SEXP type_); } #endif purrrlyr/src/fast-copy.cpp0000644000176200001440000000741113373306310015355 0ustar liggesusers// These routines were adapted from Kevin Ushey's code in hadley/reshape #include #include "utils.h" using namespace Rcpp; #define DO_REP_EACH_N(RTYPE, CTYPE, ACCESSOR) \ { \ int counter = 0; \ Shield out(Rf_allocVector(RTYPE, out_size)); \ CTYPE* x_ptr = ACCESSOR(x); \ CTYPE* out_ptr = ACCESSOR(out); \ for (int i = 0; i < x_size; ++i) { \ for (int j = 0; j < times[i]; ++j) { \ out_ptr[counter] = x_ptr[i]; \ ++counter; \ } \ } \ return out; \ break; \ } SEXP rep_each_n(const RObject x, const IntegerVector& times) { int x_size = Rf_length(x); int out_size = sum(times); switch (x.sexp_type()) { case INTSXP: DO_REP_EACH_N(INTSXP, int, INTEGER); case REALSXP: DO_REP_EACH_N(REALSXP, double, REAL); case STRSXP: { int counter = 0; Shield out(Rf_allocVector(STRSXP, out_size)); for (int i = 0; i < x_size; ++i) { for (int j = 0; j < times[i]; ++j) { SET_STRING_ELT(out, counter, STRING_ELT(x, i)); ++counter; } } return out; } case VECSXP: { int counter = 0; Shield out(Rf_allocVector(VECSXP, out_size)); for (int i = 0; i < x_size; ++i) { for (int j = 0; j < times[i]; ++j) { SET_VECTOR_ELT(out, counter, VECTOR_ELT(x, i)); ++counter; } } return out; } case LGLSXP: DO_REP_EACH_N(LGLSXP, int, LOGICAL); case CPLXSXP: DO_REP_EACH_N(CPLXSXP, Rcomplex, COMPLEX); case RAWSXP: DO_REP_EACH_N(RAWSXP, Rbyte, RAW); default: { stop("Unsupported type", type2name(x)); return R_NilValue; } } } #define DO_COPY(C_TYPE, ACCESSOR) \ { \ memcpy((char*) ACCESSOR(to) + offset_to * sizeof(C_TYPE), \ (char*) ACCESSOR(from) + offset_from * sizeof(C_TYPE), \ sizeof(C_TYPE) * n); \ return from; \ break; \ } \ SEXP copy_elements(const RObject from, int offset_from, RObject to, int offset_to, int n = 0) { // By default, copy whole 'from' vector n = n ? n : Rf_length(from) - offset_from; if (from.sexp_type() != to.sexp_type()) { stop("Incompatible slice results (types do not match)", type2name(from), type2name(to)); } if (Rf_length(to) - offset_to < n) { stop("Internal error: destination is too small"); } switch (from.sexp_type()) { case INTSXP: DO_COPY(int, INTEGER); case REALSXP: DO_COPY(double, REAL); case STRSXP: for (int i = offset_to, j = 0; j < n; ++i, ++j) { SET_STRING_ELT(to, i, STRING_ELT(from, j + offset_from)); } return to; break; case LGLSXP: DO_COPY(int, LOGICAL); case CPLXSXP: DO_COPY(Rcomplex, COMPLEX); case RAWSXP: DO_COPY(Rbyte, RAW); case VECSXP: DO_COPY(SEXP, STRING_PTR); default: stop("Unsupported type", type2name(from)); return R_NilValue; } } IntegerVector seq_each_n(const IntegerVector& times) { IntegerVector out = no_init(sum(times)); IntegerVector::iterator out_it = out.begin(); for (int i = 0; i < times.size(); ++i) { int len = times[i]; std::fill(out_it, out_it + len, i + 1); out_it += len; } return out; } purrrlyr/src/rows-data.h0000644000176200001440000000225713105124725015022 0ustar liggesusers#ifndef ROWSDATA_H #define ROWSDATA_H using namespace Rcpp; namespace rows { enum SlicesType { scalars, vectors, dataframes, nulls, objects }; enum CollationType { rows, cols, list }; struct Settings { public: CollationType collation; std::string output_colname; int include_labels; Settings(Environment execution_env_); }; struct Labels { public: int are_unique; List slicing_cols; List get() const { return labels_; } int size() const { return n_labels_; } void remove(const std::vector& index); Labels(Environment execution_env_); private: List labels_; int n_labels_; }; struct Results { public: List results; int n_slices; SlicesType type; int first_sexp_type, first_size; IntegerVector sizes; int equi_sized; std::vector empty_index; List get() { return results; } int size() { return n_slices; } Results(List raw_results_, int remove_empty_); private: int all_nulls_; void determine_first_result_properties(); void determine_null_properties(); void determine_results_properties(); void remove_empty_results(); void set_result_size(int index, int size); }; } // namespace rows #endif purrrlyr/src/init.c0000644000176200001440000000135313105124725014053 0ustar liggesusers#include #include #include // for NULL #include /* .Call calls */ extern SEXP map_impl(SEXP, SEXP, SEXP, SEXP); extern SEXP by_slice_impl(SEXP, SEXP, SEXP); extern SEXP map_by_slice_impl(SEXP, SEXP, SEXP, SEXP); extern SEXP invoke_rows_impl(SEXP, SEXP, SEXP); static const R_CallMethodDef CallEntries[] = { {"map_impl", (DL_FUNC) &map_impl, 4}, {"by_slice_impl", (DL_FUNC) &by_slice_impl, 3}, {"map_by_slice_impl", (DL_FUNC) &map_by_slice_impl, 4}, {"invoke_rows_impl", (DL_FUNC) &invoke_rows_impl, 3}, {NULL, NULL, 0} }; void R_init_purrrlyr(DllInfo *dll) { R_registerRoutines(dll, NULL, CallEntries, NULL, NULL); R_useDynamicSymbols(dll, FALSE); R_forceSymbols(dll, TRUE); } purrrlyr/src/vector.c0000644000176200001440000000514413105124725014414 0ustar liggesusers#define R_NO_REMAP #include #include #include int can_coerce(SEXPTYPE from, SEXPTYPE to) { switch(to) { case LGLSXP: return from == LGLSXP; case INTSXP: return from == LGLSXP || from == INTSXP; case REALSXP: return from == LGLSXP || from == INTSXP || from == REALSXP; case STRSXP: return from == LGLSXP || from == INTSXP || from == REALSXP || from == STRSXP; case VECSXP: return 1; } return 0; } void ensure_can_coerce(SEXPTYPE from, SEXPTYPE to, int i) { if (can_coerce(from, to)) return; Rf_errorcall(R_NilValue, "Can't coerce element %i from a %s to a %s", i + 1, Rf_type2char(from), Rf_type2char(to)); } double logical_to_real(int x) { return (x == NA_LOGICAL) ? NA_REAL : x; } double integer_to_real(int x) { return (x == NA_INTEGER) ? NA_REAL : x; } SEXP logical_to_char(int x) { if (x == NA_LOGICAL) return NA_STRING; return Rf_mkChar(x ? "TRUE" : "FALSE"); } SEXP integer_to_char(int x) { if (x == NA_INTEGER) return NA_STRING; char buf[100]; snprintf(buf, 100, "%d", x); return Rf_mkChar(buf); } SEXP double_to_char(double x) { if (!R_finite(x)) { if (R_IsNA(x)) { return NA_STRING; } else if (R_IsNaN(x)) { return Rf_mkChar("NaN"); } else if (x > 0) { return Rf_mkChar("Inf"); } else { return Rf_mkChar("-Inf"); } } char buf[100]; snprintf(buf, 100, "%f", x); return Rf_mkChar(buf); } void set_vector_value(SEXP to, int i, SEXP from, int j) { ensure_can_coerce(TYPEOF(from), TYPEOF(to), i); switch(TYPEOF(to)) { case LGLSXP: switch(TYPEOF(from)) { case LGLSXP: LOGICAL(to)[i] = LOGICAL(from)[j]; break; } break; case INTSXP: switch(TYPEOF(from)) { case LGLSXP: INTEGER(to)[i] = LOGICAL(from)[j]; break; case INTSXP: INTEGER(to)[i] = INTEGER(from)[j]; break; } break; case REALSXP: switch(TYPEOF(from)) { case LGLSXP: REAL(to)[i] = logical_to_real(LOGICAL(from)[j]); break; case INTSXP: REAL(to)[i] = integer_to_real(INTEGER(from)[j]); break; case REALSXP: REAL(to)[i] = REAL(from)[j]; break; } break; case STRSXP: switch(TYPEOF(from)) { case LGLSXP: SET_STRING_ELT(to, i, logical_to_char(LOGICAL(from)[j])); break; case INTSXP: SET_STRING_ELT(to, i, integer_to_char(INTEGER(from)[j])); break; case REALSXP: SET_STRING_ELT(to, i, double_to_char(REAL(from)[j])); break; case STRSXP: SET_STRING_ELT(to, i, STRING_ELT(from, j)); break; } break; case VECSXP: SET_VECTOR_ELT(to, i, from); break; default: Rf_errorcall(R_NilValue, "Unsupported type %s", Rf_type2char(TYPEOF(to))); } } purrrlyr/src/fast-copy.h0000644000176200001440000000043113105124725015016 0ustar liggesusers#ifndef FASTCOPY_H #define FASTCOPY_H using namespace Rcpp; SEXP rep_each_n(const RObject x, const IntegerVector& times); SEXP copy_elements(const RObject from, int offset_from, RObject to, int offset_to, int n = 0); IntegerVector seq_each_n(const IntegerVector& times); #endif purrrlyr/src/utils.h0000644000176200001440000000146414220547007014261 0ustar liggesusers#ifndef UTILS_H #define UTILS_H SEXP shadow_call(const SEXP fun, SEXP arg, SEXP dots, const SEXP env = R_NilValue); SEXP as_data_frame(SEXP x); int is_atomic(const SEXP x); int is_atomic(int x); int is_function(const SEXP fun); int is_function(int fun); SEXP get_ij_elt(const SEXP slice, int i, int j); int first_type(const Rcpp::List& results); int sexp_type(const SEXP x); void check_dataframes_consistency(const Rcpp::List x); void check_dataframes_names_consistency(const Rcpp::List& x); void check_dataframes_types_consistency(const Rcpp::List& x); // Predicates for iterator algorithms struct is_non_null : std::function { bool operator()(const SEXP x) {return !Rf_isNull(x);} }; struct is_empty : std::function { bool operator()(const SEXP x) {return Rf_length(x) == 0;} }; #endif purrrlyr/src/map.c0000644000176200001440000001330413442757560013701 0ustar liggesusers#define R_NO_REMAP #include #include #include "vector.h" void copy_names(SEXP from, SEXP to) { if (Rf_length(from) != Rf_length(to)) return; SEXP names = Rf_getAttrib(from, R_NamesSymbol); if (Rf_isNull(names)) return; Rf_setAttrib(to, R_NamesSymbol, names); } // call must involve i SEXP call_loop(SEXP env, SEXP call, int n, SEXPTYPE type) { // Create variable "i" and map to scalar integer SEXP i_val = PROTECT(Rf_ScalarInteger(1)); SEXP i = Rf_install("i"); Rf_defineVar(i, i_val, env); SEXP out = PROTECT(Rf_allocVector(type, n)); for (int i = 0; i < n; ++i) { if (i % 1000 == 0) R_CheckUserInterrupt(); INTEGER(i_val)[0] = i + 1; SEXP res = Rf_eval(call, env); if (type != VECSXP && Rf_length(res) != 1) Rf_errorcall(R_NilValue, "Result %i is not a length 1 atomic vector", i + 1); set_vector_value(out, i, res, 0); } UNPROTECT(2); return out; } SEXP map_impl(SEXP env, SEXP x_name_, SEXP f_name_, SEXP type_) { const char* x_name = CHAR(Rf_asChar(x_name_)); const char* f_name = CHAR(Rf_asChar(f_name_)); SEXP x = Rf_install(x_name); SEXP f = Rf_install(f_name); SEXP i = Rf_install("i"); SEXPTYPE type = Rf_str2type(CHAR(Rf_asChar(type_))); SEXP x_val = Rf_eval(x, env); if (Rf_isNull(x_val)) { return Rf_allocVector(type, 0); } else if (!Rf_isVector(x_val)) { Rf_errorcall(R_NilValue, "`.x` is not a vector (%s)", Rf_type2char(TYPEOF(x_val))); } int n = Rf_length(x_val); // Constructs a call like f(x[[i]], ...) - don't want to substitute // actual values for f or x, because they may be long, which creates // bad tracebacks() SEXP Xi = PROTECT(Rf_lang3(R_Bracket2Symbol, x, i)); SEXP f_call = PROTECT(Rf_lang3(f, Xi, R_DotsSymbol)); SEXP out = PROTECT(call_loop(env, f_call, n, type)); copy_names(x_val, out); UNPROTECT(3); return out; } SEXP map2_impl(SEXP env, SEXP x_name_, SEXP y_name_, SEXP f_name_, SEXP type_) { const char* x_name = CHAR(Rf_asChar(x_name_)); const char* y_name = CHAR(Rf_asChar(y_name_)); const char* f_name = CHAR(Rf_asChar(f_name_)); SEXP x = Rf_install(x_name); SEXP y = Rf_install(y_name); SEXP f = Rf_install(f_name); SEXP i = Rf_install("i"); SEXPTYPE type = Rf_str2type(CHAR(Rf_asChar(type_))); SEXP x_val = PROTECT(Rf_eval(x, env)); SEXP y_val = PROTECT(Rf_eval(y, env)); if (!Rf_isVector(x_val) && !Rf_isNull(x_val)) Rf_errorcall(R_NilValue, "`.x` is not a vector (%s)", Rf_type2char(TYPEOF(x_val))); if (!Rf_isVector(y_val) && !Rf_isNull(y_val)) Rf_errorcall(R_NilValue, "`.y` is not a vector (%s)", Rf_type2char(TYPEOF(y_val))); int nx = Rf_length(x_val), ny = Rf_length(y_val); if (nx == 0 || ny == 0) { UNPROTECT(2); return Rf_allocVector(type, 0); } if (nx != ny && !(nx == 1 || ny == 1)) { Rf_errorcall(R_NilValue, "`.x` (%i) and `.y` (%i) are different lengths", nx, ny); } int n = (nx > ny) ? nx : ny; // Constructs a call like f(x[[i]], y[[i]], ...) SEXP one = PROTECT(Rf_ScalarInteger(1)); SEXP Xi = PROTECT(Rf_lang3(R_Bracket2Symbol, x, nx == 1 ? one : i)); SEXP Yi = PROTECT(Rf_lang3(R_Bracket2Symbol, y, ny == 1 ? one : i)); SEXP f_call = PROTECT(Rf_lang4(f, Xi, Yi, R_DotsSymbol)); SEXP out = PROTECT(call_loop(env, f_call, n, type)); copy_names(x_val, out); UNPROTECT(7); return out; } SEXP pmap_impl(SEXP env, SEXP l_name_, SEXP f_name_, SEXP type_) { const char* l_name = CHAR(Rf_asChar(l_name_)); SEXP l = Rf_install(l_name); SEXP l_val = PROTECT(Rf_eval(l, env)); SEXPTYPE type = Rf_str2type(CHAR(Rf_asChar(type_))); if (!Rf_isVectorList(l_val)) Rf_errorcall(R_NilValue, "`.x` is not a list (%s)", Rf_type2char(TYPEOF(l_val))); // Check all elements are lists and find maximum length int m = Rf_length(l_val); int n = 0; for (int j = 0; j < m; ++j) { SEXP j_val = VECTOR_ELT(l_val, j); if (!Rf_isVector(j_val) && !Rf_isNull(j_val)) { Rf_errorcall(R_NilValue, "Element %i is not a vector (%s)", j + 1, Rf_type2char(TYPEOF(j_val))); } int nj = Rf_length(j_val); if (nj == 0) { UNPROTECT(1); return Rf_allocVector(type, 0); } else if (nj > n) { n = nj; } } // Check length of all elements for (int j = 0; j < m; ++j) { SEXP j_val = VECTOR_ELT(l_val, j); int nj = Rf_length(j_val); if (nj != 1 && nj != n) Rf_errorcall(R_NilValue, "Element %i has length %i, not 1 or %i.", j + 1, nj, n); } SEXP l_names = Rf_getAttrib(l_val, R_NamesSymbol); int has_names = !Rf_isNull(l_names); const char* f_name = CHAR(Rf_asChar(f_name_)); SEXP f = Rf_install(f_name); SEXP i = Rf_install("i"); SEXP one = PROTECT(Rf_ScalarInteger(1)); // Construct call like f(.x[[c(1, i)]], .x[[c(2, i)]], ...) // We construct the call backwards because can only add to the front of a // linked list. That makes PROTECTion tricky because we need to update it // each time to point to the start of the linked list. SEXP f_call = Rf_lang1(R_DotsSymbol); PROTECT_INDEX fi; PROTECT_WITH_INDEX(f_call, &fi); for (int j = m - 1; j >= 0; --j) { int nj = Rf_length(VECTOR_ELT(l_val, j)); // Construct call like .l[[c(j, i)]] SEXP j_ = PROTECT(Rf_ScalarInteger(j + 1)); SEXP ji_ = PROTECT(Rf_lang3(Rf_install("c"), j_, nj == 1 ? one : i)); SEXP l_ji = PROTECT(Rf_lang3(R_Bracket2Symbol, l, ji_)); REPROTECT(f_call = Rf_lcons(l_ji, f_call), fi); if (has_names && CHAR(STRING_ELT(l_names, j))[0] != '\0') SET_TAG(f_call, Rf_install(CHAR(STRING_ELT(l_names, j)))); UNPROTECT(3); } REPROTECT(f_call = Rf_lcons(f, f_call), fi); SEXP out = PROTECT(call_loop(env, f_call, n, type)); if (Rf_length(l_val)) { copy_names(VECTOR_ELT(l_val, 0), out); } UNPROTECT(4); return out; } purrrlyr/src/rows-formatter.cpp0000644000176200001440000002306714220547771016462 0ustar liggesusers#include #include "utils.h" #include "fast-copy.h" #include "rows-data.h" #include "rows-formatter.h" namespace rows { FormatterPtr Formatter::create(Results& results, Labels& labels, Settings& settings) { switch(settings.collation) { case rows: return FormatterPtr(new RowsFormatter(results, labels, settings)); break; case cols: return FormatterPtr(new ColsFormatter(results, labels, settings)); break; case list: return FormatterPtr(new ListFormatter(results, labels, settings)); break; } stop("Unsupported collation type."); return FormatterPtr(); } int Formatter::labels_size() { if (settings_.include_labels) return labels_.size(); else return 0; } void Formatter::check_nonlist_consistency() { switch (results_.type) { case nulls: stop("results are all NULL and can't be cols/rows collated"); break; case dataframes: check_dataframes_consistency(results_.get()); break; case objects: stop(".f must return either data frames or vectors for non-list collation"); break; default: break; } } void ColsFormatter::check_nonlist_consistency() { switch (results_.type) { case vectors: case dataframes: if (!results_.equi_sized) stop(".f should return equal length vectors or data frames for collating on `cols`"); break; default: break; } Formatter::check_nonlist_consistency(); } void ColsFormatter::adjust_results_sizes() { switch (results_.type) { case vectors: case dataframes: std::fill(results_.sizes.begin(), results_.sizes.end(), 1); break; default: break; } } void ListFormatter::adjust_results_sizes() { std::fill(results_.sizes.begin(), results_.sizes.end(), 1); } void Formatter::determine_dimensions() { if (settings_.collation == list) n_rows_ = results_.n_slices; else n_rows_ = sum(results_.sizes); n_cols_ = labels_size() + output_size(); } int RowsFormatter::output_size() { switch (results_.type) { case nulls: case scalars: return 1; break; case vectors: return 1 + should_include_rowid_column(); break; case dataframes: return Rf_length(results_.get()[0]) + should_include_rowid_column(); break; default: return -1; } } int ColsFormatter::output_size() { switch (results_.type) { case nulls: case scalars: return 1; break; case vectors: return results_.first_size; break; case dataframes: return results_.first_size * Rf_length(results_.get()[0]); break; default: return -1; break; } } int ListFormatter::output_size() { return 1; } List& Formatter::add_labels(List& out) { if (labels_size() > 0) { Rcpp::IntegerVector sizes = results_.sizes; int n_labels = labels_.slicing_cols.size(); for (int i = 0; i < n_labels; ++i) { RObject label = labels_.get()[i]; switch (sexp_type(label)) { case LGLSXP: case INTSXP: case REALSXP: case STRSXP: case CPLXSXP: case RAWSXP: case VECSXP: out[i] = rep_each_n(label, sizes); Rf_copyMostAttrib(label, out[i]); break; default: { stop("internal error: unhandled vector type in REP"); } } } } return out; } RObject Formatter::create_column(SEXPTYPE sexp_type) { if (sexp_type == NILSXP) return R_NilValue; // Copy results' list contents to a common vector. // Handles all vectors, including scalar and ragged. RObject output_col(Rf_allocVector(sexp_type, n_rows_)); for (int i = 0, counter = 0; i != results_.n_slices; ++i) { copy_elements(get_vector_elt(results_.get(), i), 0, output_col, counter); counter += results_.sizes[i]; } return output_col; } List& Formatter::maybe_create_rowid_column(List& out) { if (should_include_rowid_column()) { IntegerVector index = seq_each_n(results_.sizes); out[labels_size()] = index; } return out; } List& ListFormatter::add_output(List& out) { out[labels_size()] = results_.get(); return out; } List& RowsFormatter::rows_bind_vectors(List& out) { out = maybe_create_rowid_column(out); int index = labels_size() + should_include_rowid_column(); out[index] = create_column(results_.first_sexp_type); return out; } List& RowsFormatter::rows_bind_dataframes(List& out) { out = maybe_create_rowid_column(out); int offset = labels_size() + should_include_rowid_column(); // Fill in each column for (int col = 0; col < (n_cols_ - offset); ++col) { int type = TYPEOF(get_ij_elt(results_.get(), col, 0)); RObject vec(Rf_allocVector(type, n_rows_)); for (int s = 0, counter = 0; s < results_.size(); ++s) { copy_elements(get_ij_elt(results_.get(), col, s), 0, vec, counter); counter += results_.sizes[s]; } out[col + offset] = vec; } return out; } List& RowsFormatter::add_output(List& out) { switch (results_.type) { case nulls: case scalars: out[labels_size()] = create_column(results_.first_sexp_type); break; case vectors: out = rows_bind_vectors(out); break; case dataframes: out = rows_bind_dataframes(out); break; default: break; } return out; } List& ColsFormatter::cols_bind_vectors(List& out) { for (int i = 0, counter = 0; i < results_.first_size; ++i) { RObject out_i(Rf_allocVector(results_.first_sexp_type, n_rows_)); for (int s = 0; s < results_.size(); ++s) { copy_elements(results_.get()[s], i, out_i, counter, 1); counter += 1; } out[labels_size() + i] = out_i; counter = 0; } return out; } List& ColsFormatter::cols_bind_dataframes(List& out) { List first_result = results_.get()[0]; int n_cols_results = first_result.size(); int n_rows_results = Rf_length(first_result[0]); for (int col = 0, col_counter = 0; col < n_cols_results; ++col) { for (int row = 0, counter = 0; row < n_rows_results; ++row) { SEXPTYPE type = TYPEOF(get_vector_elt(first_result, col)); RObject out_i(Rf_allocVector(type, n_rows_)); for (int s = 0; s < results_.size(); ++s) { copy_elements(get_ij_elt(results_.get(), col, s), row, out_i, counter, 1); ++counter; } out[labels_size() + col_counter] = out_i; counter = 0; ++col_counter; } } return out; } List& ColsFormatter::add_output(List& out) { switch (results_.type) { case nulls: case scalars: out[labels_size()] = create_column(results_.first_sexp_type); break; case vectors: cols_bind_vectors(out); break; case dataframes: cols_bind_dataframes(out); break; default: break; } return out; } CharacterVector& RowsFormatter::add_rows_binded_vectors_colnames(CharacterVector& out_names) { int offset = labels_size(); if (should_include_rowid_column()) { offset += 1; out_names[labels_size()] = ".row"; } out_names[offset] = settings_.output_colname; return out_names; } CharacterVector& RowsFormatter::add_rows_binded_dataframes_colnames(CharacterVector& out_names) { int offset = labels_size(); if (!labels_.are_unique) { offset += 1; out_names[labels_size()] = ".row"; } List first_result = results_.get()[0]; CharacterVector first_colnames = first_result.names(); std::copy(first_colnames.begin(), first_colnames.end(), out_names.begin() + offset); return out_names; } List& Formatter::add_colnames(List& out) { CharacterVector out_names = no_init(n_cols_); if (labels_size() > 0) { CharacterVector slicing_cols_names = labels_.slicing_cols.names(); std::copy(slicing_cols_names.begin(), slicing_cols_names.end(), out_names.begin()); } out.names() = create_colnames(out_names); return out; } CharacterVector& RowsFormatter::create_colnames(CharacterVector& out_names) { switch (results_.type) { case nulls: case scalars: out_names[labels_size()] = settings_.output_colname; break; case vectors: out_names = add_rows_binded_vectors_colnames(out_names); break; case dataframes: out_names = add_rows_binded_dataframes_colnames(out_names); break; default: break; } return out_names; } CharacterVector& ColsFormatter::add_cols_binded_vectors_colnames(CharacterVector& out_names) { for (int i = 0; i < results_.first_size; ++i) { out_names[labels_size() + i] = settings_.output_colname + std::to_string(i + 1); } return out_names; } CharacterVector& ColsFormatter::add_cols_binded_dataframes_colnames(CharacterVector& out_names) { List first_result = results_.get()[0]; int n_cols_results = first_result.size(); int n_rows_results = Rf_length(first_result[0]); CharacterVector names(first_result.names()); for (int col = 0, counter = 0; col < n_cols_results; ++col) { for (int row = 0; row < n_rows_results; ++row) { out_names[labels_size() + counter] = (std::string) names[col] + std::to_string(row + 1); ++counter; } } return out_names; } CharacterVector& ColsFormatter::create_colnames(CharacterVector& out_names) { std::string& output_colname = settings_.output_colname; switch (results_.type) { case nulls: case scalars: out_names[labels_size()] = output_colname; break; case vectors: out_names = add_cols_binded_vectors_colnames(out_names); break; case dataframes: out_names = add_cols_binded_dataframes_colnames(out_names); break; default: break; } return out_names; } CharacterVector& ListFormatter::create_colnames(CharacterVector& out_names) { out_names[labels_size()] = settings_.output_colname; return out_names; } List Formatter::output() { determine_dimensions(); List out = no_init(n_cols_); out = add_output(out); out = add_labels(out); out = add_colnames(out); return as_data_frame(out); } } // namespace rows purrrlyr/src/utils.cpp0000644000176200001440000000543113442763341014620 0ustar liggesusers#include using namespace Rcpp; // Efficient list to data frame conversion SEXP as_data_frame(const SEXP x) { IntegerVector row_names = IntegerVector::create( IntegerVector::get_na(), -(Rf_length(get_vector_elt(x, 0))) ); Rf_setAttrib(x, Rf_install("row.names"), row_names); CharacterVector classes = CharacterVector::create("tbl_df", "tbl", "data.frame"); Rf_setAttrib(x, R_ClassSymbol, classes); return x; } int is_atomic(int x) { switch(x) { case CHARSXP: case LGLSXP: case INTSXP: case REALSXP: case CPLXSXP: case STRSXP: case RAWSXP: return 1; default: return 0; } } int is_atomic(const SEXP x) { return is_atomic(TYPEOF(x)); } int is_function(int fun) { switch(fun) { case CLOSXP: case SPECIALSXP: case BUILTINSXP: return 1; default: return 0; } } int is_function(const SEXP fun) { return is_function(TYPEOF(fun)); } SEXP get_ij_elt(const SEXP x, int i, int j) { // For rchk SEXP tmp = PROTECT(get_vector_elt(x, j)); tmp = get_vector_elt(tmp, i); UNPROTECT(1); return tmp; } int first_type(const List& results) { int type = 0, i = 0; while (i < results.size() && type == 0) { type = TYPEOF(results[i]); ++i; } return type; } int sexp_type(const SEXP x) { return TYPEOF(x); } SEXP get_element_names(const List& x, int i) { RObject subset(x[i]); return Rf_getAttrib(subset, R_NamesSymbol); } void check_dataframes_names_consistency(const List& x) { int n_protect = 0; SEXP ref = PROTECT(get_element_names(x, 0)); ++n_protect; if (TYPEOF(ref) != STRSXP) { goto error; } for (int i = 0; i < x.size(); ++i) { SEXP names = PROTECT(get_element_names(x, i)); ++n_protect; if (TYPEOF(names) != STRSXP) { goto error; } for (int j = 0; j < Rf_length(names); ++j) { SEXP x = STRING_ELT(ref, j); SEXP y = STRING_ELT(names, j); if (strcmp(CHAR(x), CHAR(y))) { goto error; }; } } UNPROTECT(n_protect); return; error: stop("data frames do not have consistent names"); } std::vector get_element_types(const List& x, int i) { List subset(x[i]); int n = subset.length(); std::vector types(n); std::transform(subset.begin(), subset.end(), types.begin(), sexp_type); return types; } void check_dataframes_types_consistency(const List& x) { std::vector ref = get_element_types(x, 0); int equi_typed = 1; for (int i = 0; i < x.size(); ++i) { std::vector names = get_element_types(x, i); equi_typed *= std::equal(ref.begin(), ref.end(), names.begin()); } if (!equi_typed) stop("data frames do not have consistent types"); } void check_dataframes_consistency(const List x) { check_dataframes_names_consistency(x); check_dataframes_types_consistency(x); } purrrlyr/src/vector.h0000644000176200001440000000051713105124725014420 0ustar liggesusers#ifndef UTILS_H #define UTILS_H // Set value of to[i] to from[j], coercing vectors using usual rules. void set_vector_value(SEXP to, int i, SEXP from, int j); // Return bool if coerceable int can_coerce(SEXPTYPE from, SEXPTYPE to); // Throw error if not coerceable void ensure_can_coerce(SEXPTYPE from, SEXPTYPE to, int i); #endif purrrlyr/src/rows-data.cpp0000644000176200001440000000634113105124725015353 0ustar liggesusers#include #include "utils.h" #include "rows-data.h" namespace rows { CollationType hash_collate(const std::string& collate) { if (collate == "rows") return rows; else if (collate == "cols") return cols; else return list; } Settings::Settings(Environment execution_env_) : output_colname(as(execution_env_[".to"])), include_labels(execution_env_[".labels"]) { collation = hash_collate(as(execution_env_[".collate"])); } Labels::Labels(Environment execution_env_) : are_unique(execution_env_[".unique_labels"]), slicing_cols(execution_env_[".slicing_cols"]), labels_(execution_env_[".labels_cols"]), n_labels_(Rf_length(execution_env_[".labels_cols"])) { } void Labels::remove(const std::vector& to_remove) { if (!to_remove.size()) return; // http://stackoverflow.com/a/22833346/946850 static Function subset("[.data.frame"); IntegerVector to_remove_neg = no_init(to_remove.size()); for (size_t i = 0; i < to_remove.size(); ++i) { to_remove_neg[i] = -to_remove[i] - 1; } List labels = labels_; // Workaround GCC -O2 crash labels_ = subset(labels, to_remove_neg, R_MissingArg); } Results::Results(List raw_results_, int remove_empty_) : results(raw_results_) { determine_first_result_properties(); if (remove_empty_) remove_empty_results(); determine_results_properties(); } void Results::determine_first_result_properties() { List::iterator first_it = std::find_if(results.begin(), results.end(), is_non_null()); if (first_it == results.end()) { all_nulls_ = 1; first_sexp_type = NILSXP; first_size = 0; } else { all_nulls_ = 0; SEXP first_result = *first_it; first_sexp_type = TYPEOF(*first_it); if (Rf_inherits(first_result, "data.frame")) first_size = Rf_length(get_vector_elt(first_result, 0)); else first_size = Rf_length(first_result); } } void Results::remove_empty_results() { List::iterator it = results.begin(); while(it != results.end()) { it = std::find_if(it, results.end(), is_empty()); if (it != results.end()) { int i = std::distance(results.begin(), it); empty_index.push_back(i); ++it; } } // Keep the empty vectors in results for now, only remove NULLs. // Useful to keep them as a mold. results.erase(std::remove(results.begin(), results.end(), R_NilValue), results.end()); } void Results::determine_results_properties() { n_slices = results.size(); sizes = (IntegerVector) no_init(n_slices); int all_df_ = all_nulls_ ? 0 : 1; int equi_typed_ = 1; equi_sized = 1; for (int i = 0; i < n_slices; ++i) { SEXP result_ = results[i]; int is_df_ = Rf_inherits(result_, "data.frame"); int result_size_ = is_df_ ? Rf_length(get_vector_elt(result_, 0)) : Rf_length(result_); all_df_ *= is_df_; equi_typed_ *= sexp_type(result_) == first_sexp_type; equi_sized *= result_size_ == first_size; sizes[i] = result_size_; } int all_atomics_ = equi_typed_ && is_atomic(first_sexp_type); if (all_atomics_) type = (equi_sized && first_size <= 1) ? scalars : vectors; else if (all_df_) type = dataframes; else if (all_nulls_) type = nulls; else type = objects; } } // namespace rows purrrlyr/src/rows.cpp0000644000176200001440000000352113652215340014442 0ustar liggesusers#include #include "map.h" #include "utils.h" #include "rows-data.h" #include "rows-formatter.h" using namespace Rcpp; namespace rows { List process_slices(List raw_results, const Environment execution_env) { rows::Settings settings(execution_env); int remove_empty = settings.collation != list; rows::Labels labels(execution_env); rows::Results results(raw_results, remove_empty); if (remove_empty) labels.remove(results.empty_index); rows::FormatterPtr formatter = rows::Formatter::create(results, labels, settings); return formatter->output(); } } // namespace rows extern "C" SEXP by_slice_impl(SEXP env, SEXP d_name_, SEXP f_name_) { BEGIN_RCPP // Map over that list SEXP results = PROTECT(map_impl(env, d_name_, f_name_, PROTECT(Rf_mkChar("list")))); // Create the output data frame results = PROTECT(rows::process_slices(results, env)); UNPROTECT(3); return results; END_RCPP } extern "C" SEXP invoke_rows_impl(SEXP env, SEXP d_name_, SEXP f_name_) { BEGIN_RCPP // Map in parallel over the rows of the data frame SEXP results = PROTECT(pmap_impl(env, d_name_, f_name_, PROTECT(Rf_mkChar("list")))); // Create the output data frame results = PROTECT(rows::process_slices(results, env)); UNPROTECT(3); return results; END_RCPP } extern "C" SEXP map_by_slice_impl(SEXP env, SEXP d_name_, SEXP f_name_, SEXP slices) { BEGIN_RCPP const char* d_name = CHAR(Rf_asChar(d_name_)); SEXP d = Rf_install(d_name); // Map over those lists for (int i = 0; i < Rf_length(slices); ++i) { Rf_defineVar(d, get_vector_elt(slices, i), env); SEXP result = PROTECT(map_impl(env, d_name_, f_name_, PROTECT(Rf_mkChar("list")))); set_vector_elt(slices, i, as_data_frame(result)); UNPROTECT(2); } // Create the output data frame return rows::process_slices(slices, env); END_RCPP } purrrlyr/src/rows-formatter.h0000644000176200001440000000517514220547475016130 0ustar liggesusers#ifndef ROWSFORMATTER_H #define ROWSFORMATTER_H #include namespace rows { class Formatter; typedef std::shared_ptr FormatterPtr; class Formatter { public: Formatter(Results& results, Labels& labels, Settings& settings) : results_(results), labels_(labels), settings_(settings) { } static FormatterPtr create(Results& results, Labels& labels, Settings& settings); virtual ~Formatter() { } List output(); protected: Results& results_; Labels& labels_; Settings& settings_; int n_rows_, n_cols_; int labels_size(); virtual void check_nonlist_consistency(); void determine_dimensions(); int should_include_rowid_column() { return !labels_.are_unique; }; List& maybe_create_rowid_column(List& out); List& add_labels(List& out); virtual int output_size() = 0; RObject create_column(SEXPTYPE type); virtual List& add_output(List& out) = 0; List& add_colnames(List& out); virtual CharacterVector& create_colnames(CharacterVector& out_names) = 0; }; class RowsFormatter : public Formatter { public: RowsFormatter(Results& results, Labels& labels, Settings& settings) : Formatter(results, labels, settings) { check_nonlist_consistency(); } private: int output_size(); List& add_output(List& out); List& rows_bind_dataframes(List& out); List& rows_bind_vectors(List& out); CharacterVector& add_rows_binded_vectors_colnames(CharacterVector& out_names); CharacterVector& add_rows_binded_dataframes_colnames(CharacterVector& out_names); CharacterVector& create_colnames(CharacterVector& out_names); }; class ColsFormatter : public Formatter { public: ColsFormatter(Results& results, Labels& labels, Settings& settings) : Formatter(results, labels, settings) { check_nonlist_consistency(); adjust_results_sizes(); } private: void check_nonlist_consistency(); void adjust_results_sizes(); int output_size(); List& add_output(List& out); List& cols_bind_dataframes(List& out); List& cols_bind_vectors(List& out); CharacterVector& add_cols_binded_vectors_colnames(CharacterVector& out_names); CharacterVector& add_cols_binded_dataframes_colnames(CharacterVector& out_names); CharacterVector& create_colnames(CharacterVector& out_names); }; class ListFormatter : public Formatter { public: ListFormatter(Results& results, Labels& labels, Settings& settings) : Formatter(results, labels, settings) { adjust_results_sizes(); } private: void adjust_results_sizes(); int output_size(); CharacterVector& create_colnames(CharacterVector& out_names); List& add_output(List& out); }; } // namespace rows #endif purrrlyr/R/0000755000176200001440000000000014024307635012360 5ustar liggesuserspurrrlyr/R/rows.R0000644000176200001440000002235713442760640013510 0ustar liggesusers#' Apply a function to slices of a data frame #' #' `by_slice()` applies `..f` on each group of a data #' frame. Groups should be set with `slice_rows()` or #' [dplyr::group_by()]. #' #' `by_slice()` provides equivalent functionality to dplyr's #' [dplyr::do()] function. In combination with #' `map()`, `by_slice()` is equivalent to #' [dplyr::summarise_each()] and #' [dplyr::mutate_each()]. The distinction between #' mutating and summarising operations is not as important as in dplyr #' because we do not act on the columns separately. The only #' constraint is that the mapped function must return the same number #' of rows for each variable mapped on. #' @param .d A sliced data frame. #' @param ..f A function to apply to each slice. If `..f` does #' not return a data frame or an atomic vector, a list-column is #' created under the name `.out`. If it returns a data frame, it #' should have the same number of rows within groups and the same #' number of columns between groups. #' @param ... Further arguments passed to `..f`. #' @param .collate If "list", the results are returned as a list- #' column. Alternatively, if the results are data frames or atomic #' vectors, you can collate on "cols" or on "rows". Column collation #' require vector of equal length or data frames with same number of #' rows. #' @param .to Name of output column. #' @param .labels If `TRUE`, the returned data frame is prepended #' with the labels of the slices (the columns in `.d` used to #' define the slices). They are recycled to match the output size in #' each slice if necessary. #' @return A data frame. #' @seealso [by_row()], [slice_rows()], #' [dmap()] #' @importFrom Rcpp sourceCpp #' @export #' @examples #' # Here we fit a regression model inside each slice defined by the #' # unique values of the column "cyl". The fitted models are returned #' # in a list-column. #' mtcars %>% #' slice_rows("cyl") %>% #' by_slice(purrr::partial(lm, mpg ~ disp)) #' #' # by_slice() is especially useful in combination with map(). #' #' # To modify the contents of a data frame, use rows collation. Note #' # that unlike dplyr, Mutating and summarising operations can be #' # used indistinctly. #' #' # Mutating operation: #' df <- mtcars %>% slice_rows(c("cyl", "am")) #' df %>% by_slice(dmap, ~ .x / sum(.x), .collate = "rows") #' #' # Summarising operation: #' df %>% by_slice(dmap, mean, .collate = "rows") #' #' # Note that mapping columns within slices is best handled by dmap(): #' df %>% dmap(~ .x / sum(.x)) #' df %>% dmap(mean) #' #' # If you don't need the slicing variables as identifiers, switch #' # .labels to FALSE: #' mtcars %>% #' slice_rows("cyl") %>% #' by_slice(purrr::partial(lm, mpg ~ disp), .labels = FALSE) %>% #' purrr::flatten() %>% #' purrr::map(coef) by_slice <- function(.d, ..f, ..., .collate = c("list", "rows", "cols"), .to = ".out", .labels = TRUE) { deprecate("by_slice() is deprecated. Please use the new colwise family in dplyr.\n", "E.g., summarise_all(), mutate_all(), etc.") ..f <- as_rows_function(..f) if (!dplyr::is.grouped_df(.d)) { stop(".d must be a sliced data frame", call. = FALSE) } if (length(.d) <= length(group_labels(.d))) { stop("Mappable part of data frame is empty", call. = FALSE) } .collate <- match.arg(.collate) set_sliced_env(.d, .labels, .collate, .to, environment(), ".d") env <- environment() env$.d <- subset_slices(.d) .Call(by_slice_impl, env, ".d", "..f") } # Prevents as_function() from transforming to a plucking function as_rows_function <- function(f, f_name = ".f") { if (inherits(f, "formula")) { as_function(f) } else if (!is.function(f)) { stop(f_name, " should be a function or a formula", call. = FALSE) } else { f } } set_sliced_env <- function(df, labels, collate, to, env, x_name) { env$.unique_labels <- TRUE env$.labels <- labels; env$.collate <- collate env$.to <- to env$.labels_cols <- group_labels(df) env$.slicing_cols <- df[names(env$.labels_cols) %||% character(0)] } #' Apply a function to each row of a data frame #' #' `by_row()` and `invoke_rows()` apply `..f` to each row #' of `.d`. If `..f`'s output is not a data frame nor an #' atomic vector, a list-column is created. In all cases, #' `by_row()` and `invoke_rows()` create a data frame in tidy #' format. #' #' By default, the whole row is appended to the result to serve as #' identifier (set `.labels` to `FALSE` to prevent this). In #' addition, if `..f` returns a multi-rows data frame or a #' non-scalar atomic vector, a `.row` column is appended to #' identify the row number in the original data frame. #' #' `invoke_rows()` is intended to provide a version of #' `pmap()` for data frames. Its default collation method is #' `"cols"`, which makes it equivalent to #' `mdply()` from the plyr package. Note that #' `invoke_rows()` follows the signature pattern of the #' `invoke` family of functions and takes `.f` as its first #' argument. #' #' The distinction between `by_row()` and `invoke_rows()` is #' that the former passes a data frame to `..f` while the latter #' maps the columns to its function call. This is essentially like #' using [invoke()] with each row. Another way to view #' this is that `invoke_rows()` is equivalent to using #' `by_row()` with a function lifted to accept dots (see #' [lift()]). #' #' @param .d A data frame. #' @param .f,..f A function to apply to each row. If `..f` does #' not return a data frame or an atomic vector, a list-column is #' created under the name `.out`. If it returns a data frame, it #' should have the same number of rows within groups and the same #' number of columns between groups. #' @param ... Further arguments passed to `..f`. #' @inheritParams by_slice #' @return A data frame. #' @seealso [by_slice()] #' @export #' @examples #' # ..f should be able to work with a list or a data frame. As it #' # happens, sum() handles data frame so the following works: #' mtcars %>% by_row(sum) #' #' # Other functions such as mean() may need to be adjusted with one #' # of the lift_xy() helpers: #' mtcars %>% by_row(purrr::lift_vl(mean)) #' #' # To run a function with invoke_rows(), make sure it is variadic (that #' # it accepts dots) or that .f's signature is compatible with the #' # column names #' mtcars %>% invoke_rows(.f = sum) #' mtcars %>% invoke_rows(.f = purrr::lift_vd(mean)) #' #' # invoke_rows() with cols collation is equivalent to plyr::mdply() #' p <- expand.grid(mean = 1:5, sd = seq(0, 1, length = 10)) #' p %>% invoke_rows(.f = rnorm, n = 5, .collate = "cols") #' \dontrun{ #' p %>% plyr::mdply(rnorm, n = 5) %>% dplyr::tbl_df() #' } #' #' # To integrate the result as part of the data frame, use rows or #' # cols collation: #' mtcars[1:2] %>% by_row(function(x) 1:5) #' mtcars[1:2] %>% by_row(function(x) 1:5, .collate = "rows") #' mtcars[1:2] %>% by_row(function(x) 1:5, .collate = "cols") by_row <- function(.d, ..f, ..., .collate = c("list", "rows", "cols"), .to = ".out", .labels = TRUE) { deprecate("`by_row()` is deprecated; please use a combination of:\n", "tidyr::nest(); dplyr::mutate(); purrr::map()") check_df_consistency(.d) if (nrow(.d) < 1) { return(.d) } ..f <- as_rows_function(..f) .collate <- match.arg(.collate) .unique_labels <- 0 .labels_cols <- .d .slicing_cols <- .d .d <- lapply(seq_len(nrow(.d)), function(i) .d[i, , drop = FALSE]) .Call(by_slice_impl, environment(), ".d", "..f") } check_df_consistency <- function(.d) { if (!is.data.frame(.d)) { stop(".d must be a data frame", call. = FALSE) } if (length(.d) == 0) { stop("Data frame is empty", call. = FALSE) } } #' @rdname by_row #' @export invoke_rows <- function(.f, .d, ..., .collate = c("list", "rows", "cols"), .to = ".out", .labels = TRUE) { deprecate("`invoke_rows()` is deprecated; please use `pmap()` instead.") check_df_consistency(.d) .collate <- match.arg(.collate) .unique_labels <- 0 .labels_cols <- .d .slicing_cols <- .d .Call(invoke_rows_impl, environment(), ".d", ".f") } #' @export #' @usage NULL #' @rdname by_row map_rows <- function(.d, .f, ..., .labels = TRUE) { deprecate("`map_rows()` is deprecated; please use `pmap()` instead.") invoke_rows(.f, .d, ..., .labels = .labels) } #' Slice a data frame into groups of rows #' #' `slice_rows()` is equivalent to dplyr's #' [dplyr::group_by()] command but it takes a vector of #' column names or positions instead of capturing column names with #' special evaluation. `unslice()` removes the slicing #' attributes. #' @param .d A data frame to slice or unslice. #' @param .cols A character vector of column names or a numeric vector #' of column positions. If `NULL`, the slicing attributes are #' removed. #' @return A sliced or unsliced data frame. #' @seealso [by_slice()] and [dplyr::group_by()] #' @export slice_rows <- function(.d, .cols = NULL) { deprecate("`slice_rows()` is deprecated; please use `dplyr::group_by()` instead.") stopifnot(is.data.frame(.d)) if (is.null(.cols)) { return(unslice(.d)) } if (is.numeric(.cols)) { .cols <- names(.d)[.cols] } stopifnot(is.character(.cols)) dplyr::group_by_at(.d, .cols) } #' @rdname slice_rows #' @export unslice <- function(.d) { deprecate("`unslice()` is deprecated; please use `dplyr::ungroup()` instead.") dplyr::ungroup(.d) } purrrlyr/R/purrrlyr.R0000644000176200001440000000006213105124725014376 0ustar liggesusers#' @useDynLib purrrlyr, .registration = TRUE NULL purrrlyr/R/utils.R0000644000176200001440000000143613373247145013654 0ustar liggesusers#' Pipe operator #' #' @name %>% #' @rdname pipe #' @keywords internal #' @export #' @importFrom magrittr %>% #' @usage lhs \%>\% rhs NULL names2 <- function(x) { names(x) %||% rep("", length(x)) } `%||%` <- function(x, y) { if (is.null(x)) { y } else { x } } isFALSE <- function(x) identical(x, FALSE) ndots <- function(...) nargs() inv_which <- function(x, sel) { if (is.character(sel)) { names <- names(x) if (is.null(names)) { stop("character indexing requires a named object", call. = FALSE) } names %in% sel } else if (is.numeric(sel)) { seq_along(x) %in% sel } else { stop("unrecognised index type", call. = FALSE) } } deprecate <- function(...) { # No message for now } as_function <- function(...) { purrr::as_mapper(...) } purrrlyr/R/dplyr.R0000644000176200001440000000067213431472417013644 0ustar liggesusers #' @importFrom dplyr group_data group_labels <- function(data) { dplyr::select(group_data(data), -".rows") } group_sizes <- function(data) { lengths(group_data(data)$.rows) } subset_slices <- function(data, keep_groups = FALSE) { if (!dplyr::is_grouped_df(data)) { return(list(data)) } cols <- setdiff(names(data), dplyr::group_vars(data)) indices <- group_data(data)$.rows lapply(indices, function(x) data[x, cols]) } purrrlyr/R/dmap.R0000644000176200001440000000557313442760531013437 0ustar liggesusers#' Map over the columns of a data frame #' #' `dmap()` is just like [purrr::map()] but always returns a #' data frame. In addition, it handles grouped or sliced data frames. #' #' `dmap_at()` and `dmap_if()` recycle length 1 vectors to #' the group sizes. #' @inheritParams purrr::map #' @inheritParams purrr::as_function #' @inheritParams purrr::map_if #' @param .d A data frame. #' @export #' @examples #' # dmap() always returns a data frame: #' dmap(mtcars, summary) #' #' # dmap() also supports sliced data frames: #' sliced_df <- mtcars[1:5] %>% slice_rows("cyl") #' sliced_df %>% dmap(mean) #' sliced_df %>% dmap(~ .x / max(.x)) #' #' # This is equivalent to the combination of by_slice() and dmap() #' # with 'rows' collation of results: #' sliced_df %>% by_slice(dmap, mean, .collate = "rows") dmap <- function(.d, .f, ...) { deprecate("dmap() is deprecated. Please use the new colwise family in dplyr.\n", "E.g., summarise_all(), mutate_all(), etc.") .f <- as_function(.f, ...) if (dplyr::is.grouped_df(.d)) { sliced_dmap(.d, .f, ...) } else { res <- .Call(map_impl, environment(), ".d", ".f", "list") dplyr::as_tibble(res) } } sliced_dmap <- function(.d, .f, ...) { if (length(.d) <= length(group_labels(.d))) { .d } else { set_sliced_env(.d, TRUE, "rows", "", environment(), ".d") slices <- subset_slices(.d) .Call(map_by_slice_impl, environment(), ".d", ".f", slices) } } #' @rdname dmap #' @export dmap_at <- function(.d, .at, .f, ...) { deprecate("dmap_at() is deprecated. Please use the new colwise family in dplyr.\n", "E.g., summarise_at(), mutate_at(), etc.") sel <- inv_which(.d, .at) partial_dmap(.d, sel, .f, ...) } #' @rdname dmap #' @export dmap_if <- function(.d, .p, .f, ...) { deprecate("dmap_if() is deprecated. Please use the new colwise family in dplyr.\n", "E.g., summarise_if(), mutate_if(), etc.") sel <- purrr::map_lgl(.d, .p) partial_dmap(.d, sel, .f, ...) } partial_dmap <- function(.d, .sel, .f, ...) { .f <- as_function(.f) subset <- dplyr::select(.d, !!dplyr::group_vars(.d), !!names(.d)[.sel]) set_sliced_env(.d, FALSE, "rows", "", environment(), "slices") slices <- subset_slices(subset) res <- .Call(map_by_slice_impl, environment(), "slices", ".f", slices) res <- dmap_recycle(res, .d) .d[.sel] <- res .d } dmap_recycle <- function(res, d) { if (dplyr::is.grouped_df(d)) { return(dmap_recycle_sliced(res, d)) } if (!nrow(res) %in% c(0, 1, nrow(d))) { stop("dmap() only recycles vectors of length 1", call. = TRUE) } res } dmap_recycle_sliced <- function(res, d) { if (nrow(res) == nrow(d)) { return(res) } if (nrow(group_labels(d)) == nrow(res)) { sizes <- group_sizes(d) indices <- purrr::map2(seq_len(nrow(res)), sizes, ~rep(.x, each = .y)) res <- res[purrr::flatten_int(indices), ] return(res) } stop("dmap() only recycles vectors of length 1") } purrrlyr/NEWS.md0000644000176200001440000000352014220553217013252 0ustar liggesusers# purrrlyr 0.0.8 * Fixes for CRAN checks. * purrrlyr no longer depends on BH headers. # purrrlyr 0.0.7 * Fixed CRAN checks with r-devel. # purrrlyr 0.0.6 * Compatibility with dplyr 1.0. # purrrlyr 0.0.5 * Fixed protection issues reported by rchk. # purrrlyr 0.0.4 * Compatibility with dplyr 0.8.0. * Compatibility with R 3.5. # purrrlyr 0.0.3 * Fixed a compilation issue with clang and libc++. # purrlyr 0.0.2 CRAN maintenance release. # purrlyr 0.0.1 All data-frame based mappers have been moved to this package. These functions are not technically deprecated (so you can move to this package as easily as possible), but these functions are unlikely to be changed in the future (i.e. there will be no bug fixes) and are likely to go away in the near future, so we highly recommend updating to new approaches. * Mapping a function to each column of a data frame should now be handled with the colwise mutating and summarising operations in dplyr instead of `dmap()`. These are the verbs with suffix `_all()`, `_at()` and `_if()`, such as `mutate_all()` or `summarise_if()`. Note that this means the output of `.f` should conform to the requirements of dplyr operations: same length as the input for mutating operations, and length 1 for summarising operations. * Inovking a function row by row with the columns of a data frame as arguments should be done with `pmap()` followed by `dplyr::as_dataframe()` instead of `map_rows()`. * Mapping rowwise slices of a data frame with `by_row()` is deprecated in favour of a combination of tidyverse functions. First use `tidyr::nest()` to create a list-column containing groupwise data frames. Then use `dplyr::mutate()` to operate on this list-column. Typically you will want to apply a function on each element (nested data frame) of this list-column with `purrr::map()`. purrrlyr/MD50000644000176200001440000000310114220601322012446 0ustar liggesusersf84098fe62685a7199027cf55603fd4c *DESCRIPTION d32239bcb673463ab874e80d47fae504 *LICENSE f98812b13fa0df9406555089a6cbb0d3 *NAMESPACE d65426bc64dc0e492606673a38dad523 *NEWS.md d0ba00c8d2e1b384e6b4f2956a46dbe3 *R/dmap.R 122b7acb110dc03ac70e4d3a5ffc87cf *R/dplyr.R 710ea2e0500586e2b1700f0beeebf2fe *R/purrrlyr.R 1ed9d481516d52396edf13632b719c06 *R/rows.R cbafc156f23bd23268f0d2d53ad3f2c9 *R/utils.R 49f911a734a0d6ed3fc462e25edbc092 *README.md 577a31f541257b3def7139c74b004b1e *man/by_row.Rd 333c13c6392b6133fc8db291663428ec *man/by_slice.Rd dd3aeef2ca08c5c5442ffcc12bcef650 *man/dmap.Rd a64a7ea44fcaa33c2d3ad0f7909cbc3e *man/pipe.Rd 955d28473518cd6a798082c80afd61af *man/slice_rows.Rd c6269c0dc42fdafe8088e2d1a16b8c7a *src/fast-copy.cpp 03472628c635c2684b8f9647d90e6aa4 *src/fast-copy.h e696d04a57622d6ca77e1d6378810b28 *src/init.c fbd8f84bb91a74d22d517dcd5055eb33 *src/map.c daa7efc01a8489ded96d8c0863e69b0f *src/map.h e6d1a2bddc8db28198e5ce9163aba317 *src/rows-data.cpp dbd3473711e1c2459624ade21e525bf1 *src/rows-data.h b14bc5ac596aac76d0cd243cf39e6927 *src/rows-formatter.cpp 022d7d07d0d86d165c32abedc0d3d9cd *src/rows-formatter.h 6a2a2baec21a475bf59930ceb1b29a68 *src/rows.cpp 01369809b54adaed8226f1b3a5582f5e *src/utils.cpp 4fd622a8cb8da0c8295a2098f72ae17a *src/utils.h 34bfa239377d45bd475371872444eb66 *src/vector.c 765334f19be0310a201e7b97f270709a *src/vector.h 58e0794410bf1881b9b841e965e5a022 *tests/testthat.R 0529b8853f563f7310c10cd4f93ae52b *tests/testthat/helper-rows.R d656bd8655e0ead17d1117db70b7967d *tests/testthat/test-dmap.R fa519937baf11908c3329db4b10a1f65 *tests/testthat/test-rows.R