diff --git a/.RData b/.RData new file mode 100644 index 0000000..c8ef85f Binary files /dev/null and b/.RData differ diff --git a/.gitignore b/.gitignore deleted file mode 100644 index fae8299..0000000 --- a/.gitignore +++ /dev/null @@ -1,39 +0,0 @@ -# History files -.Rhistory -.Rapp.history - -# Session Data files -.RData - -# User-specific files -.Ruserdata - -# Example code in package build process -*-Ex.R - -# Output files from R CMD build -/*.tar.gz - -# Output files from R CMD check -/*.Rcheck/ - -# RStudio files -.Rproj.user/ - -# produced vignettes -vignettes/*.html -vignettes/*.pdf - -# OAuth2 token, see https://github.com/hadley/httr/releases/tag/v0.3 -.httr-oauth - -# knitr and R markdown default cache directories -*_cache/ -/cache/ - -# Temporary files created by R markdown -*.utf8.md -*.knit.md - -# R Environment Variables -.Renviron diff --git a/.rprofile b/.rprofile new file mode 100644 index 0000000..96f2b14 --- /dev/null +++ b/.rprofile @@ -0,0 +1,69 @@ +print ("Bonjour") + +# library (FactoMineR) +# library (car) +# library (doBy) +library (openxlsx) +library(rstatix) +# library (Factoshiny) + +####################################################### +# la fonction coller permet de faire une importation par +coller = function () +{ + read.table("clipboard", header=TRUE, sep="\t", dec = ",") +} +####################################################### +# permet d'importer de l'Excel +ie = function () +{ + read.xlsx( file.choose() ) +} + +####################################################### +# Extraction des colonnes numériques d'un dataframe +DfNum = function(DataFrameEntree) +{ + DataFrameSortie = DataFrameEntree [ sapply ( X = DataFrameEntree, is.numeric ) == TRUE] + return(DataFrameSortie) +} + +############################################################################################ +# Fonction qui effectue le test du Khi Deux des combinaisons des variables d'un dataframe +FKhiDeux = function (DataFrameEntree) +{ + # Récupère le nom du DataFrame passé en entrée + NomDataFrame = deparse(substitute(DataFrameEntree)) + + # Récupère les noms des colonnes du dataframe + DataFrameEntree = DfTexte(DataFrameEntree) + NomVariables = names (DataFrameEntree) + + # Crée un dataframe avec 2 colonnes contenant toutes ls combinaisons croisées des Noms des variables + DataFrameSortie = as.data.frame(t(combn(x=NomVariables, m = 2))) + + i = 1 + while (i<=nrow(DataFrameSortie)) + { + # Récupération de la p-value + PValueLocale = + chisq.test( + DataFrameEntree [,DataFrameSortie [i,1]], + DataFrameEntree [,DataFrameSortie [i,2]] + )$p.value + + # Stockage de la p-value du test du Khi ² + DataFrameSortie$PValueKhiDeux [i] = PValueLocale + i = i + 1 + } + + # Ajout de la colonne SIGnificatif ou pas (avec un alpha de 0.05) + + DataFrameSortie$Sig = ifelse(DataFrameSortie$PValueKhiDeux<0.05, "SIG", "NON SIG") + + # Retour du dataframe de synthèse + return (DataFrameSortie) +} +##################################################################################### + +print ("A Bientôt!!") diff --git a/LICENSE b/LICENSE deleted file mode 100644 index f288702..0000000 --- a/LICENSE +++ /dev/null @@ -1,674 +0,0 @@ - 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 -. diff --git "a/Mod\303\251lisation.R" "b/Mod\303\251lisation.R" deleted file mode 100644 index 16882f4..0000000 --- "a/Mod\303\251lisation.R" +++ /dev/null @@ -1,676 +0,0 @@ -### Modélisation ! -library(magrittr) # paquetage nécessaire pour utiliser le tuyau ou pipe de programmation -library(gapminder) -library(tidyverse) -library(SmartEDA) -library(corrplot) -library(RColorBrewer) -library(ggthemes) -library(ggpubr) -library(knitr) -library(rmarkdown) -library(markdown) -### définition du répertoire de travail ---- -setwd("c:/Cours_R") ### changez cela dans votre environnement -getwd() # afficher le répertoire de travail. -theme_set(theme_bw()) # -(.packages()) - -### modéle sur les données gapmind 2007 2019 ------ -# lancement de paquetages -library(estimatr) # procédures d'estimation optimisées -library(AER) # paquetage d'économétrie complet -library(olsrr) # suite complète d'estimations et tes avec ols -# https://olsrr.rsquaredacademy.com/index.html -library(mctest) # paquetage complet de diagnostics de colinéarité -(.packages()) - -### un premier modéle ols... -mco1 <- lm(log(GDI_2019) ~ log(GNI_2019/pop_2019), data = gapmind_2007_19) -mco1 -smco1 <- summary(mco1) -smco1 -#### observons l'objet modéle: -class(mco1) -mode(mco1) -str(mco1) -View(mco1) -plot(mco1) -### explication des graphiques de diagnostic de regression: -# http://www.sthda.com/english/articles/39-regression-model-diagnostics/161-linear-regression-assumptions-and-diagnostics-in-r-essentials/ - -install.packages("devtools") -devtools::install_github("cardiomoon/ggiraphExtra") - -### afficher les noms d'une liste ou d'un objet: -names(mco1) -names(gapmind_2007_19) -names(smco1) -View(smco1) - -### éa marche pour presque tout: -names(gapmind_2007) -names(gdignilog) - -### on va tenter de prédire GDI_2019 avec gdpPercap 2007 qui n'a pas de NA ! -summary(gapmind_2007_19$GDI_2019) -summary(gapmind_2007_19$gdpPercap) -### modèle 2: ajustement de GDI_2019 par gdppc 2007 (sans NA) -mco2 <- (log(GDI_2019) ~ log(gdpPercap), - data = filter(gapmind_2007_19, !is.na(gapmind_2007_19$GDI_2019))) -smco2 <- summary(mco2) -smco2 -smco1 -plot(mco2) -### utilisons les valeurs de gdpPercap pour prédire les NAs de GDI_2019 -gdipred2 <- filter(gapmind_2007_19$GDI_2019, is.na(gapmind_2007_19$GDI_2019)) -## ou bien ce que nous avions calculé: -gdipred2 <- gapmind_07_19_na -names(gdipred2) -glimpse(gdipred2) -yhat.mco2 <- predict(mco2, gdipred2) -yhat.mco2 -### en fait on peut tout faire en ggplot ! -# https://ggplot2.tidyverse.org/reference/fortify..html -head(fortify(mco2), 25) ### on va utiliser fortify mais broom devrait étre bien mieux ! -### rappeler les graphiques de diagnostic -plot(mco2, which = 1:6) - -##### modèle MCO 4 -mco4 <- lm(log(GDI_2019) ~ log(gdpPercap), - weights = pop, - data = filter(gapmind_2007_19, !is.na(gapmind_2007_19$GDI_2019))) -smco4 <- summary(mco4) -smco4 -plot(mco4, which = 1:6) - -### on peut regarder le modéle avec les ggplots via fortify: -ggplot(mco2, aes(.fitted, .resid)) + - geom_point() + - geom_hline(yintercept = 0) + - geom_smooth(se = FALSE) - -ggplot(mco2, aes(.fitted, .stdresid)) + - geom_point() + - geom_hline(yintercept = c(-2,0,2), colour = "red") + - geom_smooth(se = FALSE) - -ggplot(mco4, aes(.fitted, .resid)) + - geom_point() + - geom_hline(yintercept = 0) + - geom_smooth(se = FALSE) - -ggplot(mco4, aes(.fitted, .stdresid)) + - geom_point() + - geom_hline(yintercept = c(-2,0,2)) + - geom_smooth(se = FALSE) - -#### en fait on avait un tibble filtré sans na sur gdi_2019: -mco3 <- lm(log(GDI_2019) ~ log(gdpPercap), data = gapmind_07_19_gdi) -smco3 <- summary(mco3) -smco3 -plot(mco3) ### c'est le méme modéle mais les données sont compatibles ! -ggplot(mco3, aes(.fitted, .resid)) + - geom_point() + - geom_hline(yintercept = 0) + - geom_smooth(se = FALSE) - -ggplot(fortify(mco3, gapmind_07_19_gdi), aes(.fitted, .stdresid)) + - geom_point(aes(color = HDI_Class, shape = continent)) + - geom_hline(yintercept = 0) + - geom_smooth(se = FALSE) + - scale_color_brewer(palette = "Dark2") + - labs(title = "Graphique ajustement vs. résidus", - subtitle = "Résidus studentisés", - x = "Valeurs ajustées", y = "Résidus studentisés", - caption = "Modèle 3, lnGDI_2019 ~ lngdpPercap_2007", - color = "Classe d'HDI") + - scale_color_discrete(name = "Classe d'HDI", labels = c("Haute", "Basse", "Moyenne", "Très haute")) + - scale_shape_discrete(name = "Continent", labels = c("Afrique", "Amérique", "Asie", "Europe", "Océanie")) - -### graphe quantile quantile des résidus -ggplot(mco3) + - stat_qq(aes(sample = .stdresid)) + - geom_abline(color = "red") + - geom_vline(xintercept = c(-2, 2), color = "blue") + - geom_hline(yintercept = 0) - -### mais on peut aussi le calculer selon les facteurs actifs: -ggplot(fortify(mco3, gapmind_07_19_gdi), aes(color = HDI_Class, shape = continent)) + - stat_qq(aes(sample = .stdresid)) + - geom_abline(color = "red") + - geom_vline(xintercept = c(-2, 2), color = "blue") + - labs(title = "Graphique quantiles-quantiles des résidus", - subtitle = "Résidus studentisés", - x = "Quantile théoriques", y = "Quantiles empiriques", - caption = "Modèle 3, lnGDI_2019 ~ lngdpPercap_2007", - color = "Classe d'HDI") + - scale_color_discrete(name = "Classe d'HDI", - labels = c("Haute", "Basse", "Moyenne", "Très haute")) + - scale_shape_discrete(name = "Continent", - labels = c("Afrique", "Amérique", "Asie", "Europe", "Océanie")) - - -### on peut appliquer notre esthétique sur les données du qq plot: -ggplot(fortify(mco3, gapmind_07_19_gdi), aes(color = HDI_Class)) + - stat_qq(aes(sample = .stdresid)) + - stat_qq_line(aes(sample = .stdresid)) + - geom_abline(color = "red") + - geom_vline(xintercept = c(-2, 2), color = "blue") + - labs(title = "Graphique quantiles-quantiles des résidus selon l'HDI", - subtitle = "Résidus studentisés", - x = "Quantile théoriques", y = "Quantiles empiriques", - caption = "Modéle 3, lnGDI_2019 ~ lngdpPercap_2007", - color = "Classe d'HDI") + - scale_color_discrete(name = "Classe d'HDI", - labels = c("Haute", "Basse", "Moyenne", "Très haute")) - -### mais on peut aussi le calculer selon les facteurs actifs: -ggplot(fortify(mco3, gapmind_07_19_gdi), aes(color = continent)) + - stat_qq(aes(sample = .stdresid)) + - stat_qq_line(aes(sample = .stdresid)) + - geom_abline(color = "red", linetype = 3) + # attention, l'esthétique doit s'appliquer é *._line - geom_vline(xintercept = c(-2, 2), color = "blue", linetype = 2) + - labs(title = "Graphique quantiles-quantiles des résidus selon le continent", - subtitle = "Résidus studentisés", - x = "Quantile théoriques", y = "Quantiles empiriques", - caption = "Modéle 3, lnGDI_2019 ~ lngdpPercap_2007", - color = "Continent") + - scale_color_discrete(name = "Continent", labels = c("Afrique", "Amérique", "Asie", "Europe", "Océanie")) - -### on peut regarder les résidus absolus: ---- -plot(mco3, which = 3) -# same ggplot: -ggplot(mco3, aes(.fitted, sqrt(abs(.stdresid)))) + - geom_point() + - geom_smooth(se = FALSE) -### soit: -ggplot(fortify(mco3, gapmind_07_19_gdi), aes(.fitted, sqrt(abs(.stdresid)))) + - geom_point(aes(color = HDI_Class)) + - geom_hline(color = "blue", linetype = 3, yintercept = 2.0) + - geom_smooth(se = FALSE) + - labs(title = "Graphique échelle-localisation", - subtitle = "Racine carrée des résidus standardisés", - x = "Valeurs ajustées", y = "Racine carrée des résidus standardisés", - caption = "Modéle 3, lnGDI_2019 ~ lngdpPercap_2007", - color = "Classe d'HDI") + - scale_color_discrete(name = "Classe d'HDI", labels = c("Haute", "Basse", "Moyenne", "Très haute")) - - -### distances de Cook ---- -plot(mco3, which = 4) -### en ggplot frustre: -ggplot(mco3, aes(seq_along(.cooksd), .cooksd)) + - geom_col() -smco3 - -### effet intéressant quand on applique l'esthétiue par collage de la commande: -ggplot(fortify(mco3, gapmind_07_19_gdi), aes(seq_along(.cooksd), .cooksd)) + - geom_col(aes(color = HDI_Class)) # collage de color ! -# rectification par fill. -ggplot(fortify(mco3, gapmind_07_19_gdi), aes(seq_along(.cooksd), .cooksd)) + - geom_col(aes(fill = HDI_Class)) + # collage de color ! - geom_hline(color = "blue", linetype = 2, yintercept = 0.1) + -labs(title = "Graphique des distances de Cook", - subtitle = "Indicateur d'influence des observations", - x = "Index", y = "Distances de Cook", - caption = "Modèle 3, lnGDI_2019 ~ lngdpPercap_2007", - color = "Classe d'HDI") + # pourrait ajouter la palette Rcolorbrewer - scale_fill_discrete(name = "Classe d'HDI", labels = c("Haute", "Basse", "Moyenne", "Très haute")) - - -### Graphiques Résidus vs levier ---- -plot(mco3, which = 5) -### ggplot simple: -ggplot(mco3, aes(.hat, .stdresid)) + - geom_vline(size = 2, colour = "white", xintercept = 0) + - geom_hline(size = 2, colour = "white", yintercept = 0) + - geom_point() + geom_smooth(se = FALSE) -### ggplot amélioré: -ggplot(fortify(mco3, gapmind_07_19_gdi), aes(.hat, .stdresid)) + - geom_vline(size = 0.5, colour = "red", xintercept = 0) + - geom_hline(size = 0.5, colour = "red", yintercept = 0) + - geom_point(aes(color = HDI_Class)) + - geom_smooth(se = FALSE) + - labs(title = "Graphique des résidus vs leviers", - subtitle = "Indicateur d'influence des observations sur les résidus", - x = "Leviers", y = "Distances de Cook", - caption = "Modéle 3, lnGDI_2019 ~ lngdpPercap_2007", - color = "Classe d'HDI") + # pourrait ajouter la palette Rcolorbrewer - scale_color_discrete(name = "Classe d'HDI", - labels = c("Haute", "Basse", "Moyenne", "Très haute")) - -### on peut jouer sur la taille avec size dans geom point ! -ggplot(fortify(mco3, gapmind_07_19_gdi), aes(.hat, .stdresid)) + - geom_vline(size = 0.5, xintercept = 0) + - geom_hline(size = 0.5, yintercept = 0) + - geom_point(aes(color = HDI_Class, size = .cooksd)) + - geom_smooth(se = FALSE, size = 0.5) + - labs(title = "Graphique des résidus vs leviers", - subtitle = "Indicateur d'influence des observations sur les résidus", - x = "Leviers", y = "Résidus standardisés", - caption = "Modéle 3, lnGDI_2019 ~ lngdpPercap_2007", - color = "Classe d'HDI") + # pourrait ajouter la palette Rcolorbrewer - scale_color_discrete(name = "Classe d'HDI", - labels = c("Haute", "Basse", "Moyenne", "Très haute")) - -### graphique Cook -- Leviers -plot(mco3, which = 6) # le sixiéme graphique de diagnostic ! -### ggplot basic -ggplot(mco3, aes(.hat, .cooksd)) + - geom_vline(xintercept = 0, colour = NA) + - geom_abline(slope = seq(0, 3, by = 0.5), colour = "white") + - geom_smooth(se = FALSE) + - geom_point() -### ggplot amélioré -ggplot(fortify(mco3, gapmind_07_19_gdi), aes(.hat, .cooksd)) + - geom_vline(xintercept = 0, colour = NA) + - geom_abline(slope = seq(0, 3, by = 0.5), colour = "red", linetype = 2) + # esthétiques de geom_line() - geom_smooth(se = FALSE) + - geom_point(aes(color = HDI_Class)) + - labs(title = "Graphique des leviers vs distances de Cook", - subtitle = "Levier = hii / (1 - hii)", - x = "Leviers", y = "Distances de Cook", - caption = "Modéle 3, lnGDI_2019 ~ lngdpPercap_2007", - color = "Classe d'HDI") - -### on peut aussi modifier l'esthétique en faisant le ratio cook/hat: -ggplot(mco3, aes(.hat, .cooksd)) + - geom_point(aes(size = .cooksd / .hat)) + - scale_size_area() -# amélioré: -ggplot(fortify(mco3, gapmind_07_19_gdi), aes(.hat, .cooksd)) + - geom_vline(xintercept = 0, colour = NA) + - geom_abline(slope = seq(0, 3, by = 0.5), colour = "red", linetype = 2) + # esthétiques de geom_line() - geom_smooth(se = FALSE) + - geom_point(aes(color = HDI_Class, size = .cooksd / .hat)) + - scale_size_area() + - labs(title = "Graphique des leviers vs distances de Cook", - subtitle = "Levier = hii / (1 - hii)", - x = "Leviers", y = "Distances de Cook", - caption = "Modéle 3, lnGDI_2019 ~ lngdpPercap_2007", - color = "Classe d'HDI") - -### on voit donc la richesse des graphiques de diagnostic de régression ! - -#### regardons avec broom les mises en formes de modéles... ---- -install.packages("broom") -install.packages("broomhelpers") -install.packages("tidymodels") -install.packages("finalfit") -library(broom) -library(broom.helpers) -library(tidymodels) -library(finalfit) -### https://broom.tidymodels.org/ -### https://www.tidymodels.org/ -### https://finalfit.org/reference/finalfit.html - -### la base: le modéle 3: -mco3 # le plus compact: l'objet associé au modéle... -summary(mco3) # un peu plus complet... mais... -# regardons le bazar: -str(mco3) - -mco3$coefficients -mco3$residuals -mco3$fitted.values -names(mco3) - -### avec broom on transforme les modéles bazars en beaux tibbles ! -t.mco3 <- tidy(mco3) # ah c'est plus beau ! -glimpse(t.mco3) -# noter la colonne terme accessible avec $ ! -aug.mco3 <- augment(mco3) # on a un équivalent élargi du modéle -View(aug.mco3) -g.mco3 <- glance(mco3) # coup d'oeil aux diagnostics de régression ! -### accéder aux objets modéle ---- -names(mco3) -modele_3 <- c(t.mco3, aug.mco3, g.mco3) -modele_3 -str(modele_3) - -#### modele mco 4 ----- -plot(mco4) ### c'est le méme modéle mais les données sont compatibles ! -ggplot(mco4, aes(.fitted, .resid)) + - geom_point() + - geom_hline(yintercept = 0) + - geom_smooth(se = FALSE) - -ggplot(fortify(mco4, gapmind_07_19_gdi), aes(.fitted, .stdresid)) + - geom_point(aes(color = HDI_Class, shape = continent)) + - geom_hline(yintercept = 0) + - geom_hline(yintercept = c(-2.5, 2.5), linetype = 2, color = "red") + - geom_smooth(se = FALSE) + - scale_color_brewer(palette = "Dark2") + - labs(title = "Graphique ajustement vs. résidus", - subtitle = "Résidus studentisés", - x = "Valeurs ajustées", y = "Résidus studentisés", - caption = "Modéle 3, lnGDI_2019 ~ lngdpPercap_2007", - color = "Classe d'HDI") + - scale_color_discrete(name = "Classe d'HDI", labels = c("Haute", "Basse", "Moyenne", "Trés haute")) + - scale_shape_discrete(name = "Continent", labels = c("Afrique", "Amérique", "Asie", "Europe", "Océanie")) - -### graphe quantile quantile des résidus -ggplot(mco4) + - stat_qq(aes(sample = .stdresid)) + - geom_abline(color = "red") + - geom_vline(xintercept = c(-2, 2), color = "blue") + - geom_hline(yintercept = 0) - -### mais on peut aussi le calculer selon les facteurs actifs: -ggplot(fortify(mco4, gapmind_07_19_gdi), aes(color = HDI_Class, shape = continent)) + - stat_qq(aes(sample = .stdresid)) + - geom_abline(color = "red") + - geom_vline(xintercept = c(-2, 2), color = "blue") + - geom_hline(yintercept = c(-2.5, 2.5), linetype = 2, color = "blue") + - labs(title = "Graphique quantiles-quantiles des résidus", - subtitle = "Résidus studentisés", - x = "Quantile théoriques", y = "Quantiles empiriques", - caption = "Modéle 3, lnGDI_2019 ~ lngdpPercap_2007", - color = "Classe d'HDI") + - scale_color_discrete(name = "Classe d'HDI", - labels = c("Haute", "Basse", "Moyenne", "Trés haute")) + - scale_shape_discrete(name = "Continent", - labels = c("Afrique", "Amérique", "Asie", "Europe", "Océanie")) - - -### on peut appliquer notre esthétique sur les données du qq plot: -ggplot(fortify(mco4, gapmind_07_19_gdi), aes(color = HDI_Class)) + - stat_qq(aes(sample = .stdresid)) + - stat_qq_line(aes(sample = .stdresid)) + - geom_abline(color = "red") + - geom_vline(xintercept = c(-2, 2), color = "blue") + - labs(title = "Graphique quantiles-quantiles des résidus selon l'HDI", - subtitle = "Résidus studentisés", - x = "Quantile théoriques", y = "Quantiles empiriques", - caption = "Modéle 3, lnGDI_2019 ~ lngdpPercap_2007", - color = "Classe d'HDI") + - scale_color_discrete(name = "Classe d'HDI", - labels = c("Haute", "Basse", "Moyenne", "Trés haute")) - -### mais on peut aussi le calculer selon les facteurs actifs: -ggplot(fortify(mco4, gapmind_07_19_gdi), aes(color = continent)) + - stat_qq(aes(sample = .stdresid)) + - stat_qq_line(aes(sample = .stdresid)) + - geom_abline(color = "red", linetype = 3) + # attention, l'esthétique doit s'appliquer é *._line - geom_vline(xintercept = c(-2, 2), color = "blue", linetype = 2) + - geom_hline(yintercept = c(-2.5, 2.5), linetype = 2, color = "blue") + - labs(title = "Graphique quantiles-quantiles des résidus selon le continent", - subtitle = "Résidus studentisés", - x = "Quantile théoriques", y = "Quantiles empiriques", - caption = "Modéle 3, lnGDI_2019 ~ lngdpPercap_2007", - color = "Continent") + - scale_color_discrete(name = "Continent", labels = c("Afrique", "Amérique", "Asie", "Europe", "Océanie")) - -### on peut regarder les résidus absolus: ---- -plot(mco4, which = 3) -# same ggplot: -ggplot(mco4, aes(.fitted, sqrt(abs(.stdresid)))) + - geom_point() + - geom_smooth(se = FALSE) -### soit: -ggplot(fortify(mco4, gapmind_07_19_gdi), aes(.fitted, sqrt(abs(.stdresid)))) + - geom_point(aes(color = HDI_Class)) + - geom_hline(color = "blue", linetype = 3, yintercept = 2.0) + - geom_smooth(se = FALSE) + - labs(title = "Graphique échelle-localisation", - subtitle = "Racine carrée des résidus standardisés", - x = "Valeurs ajustées", y = "Racine carrée des résidus standardisés", - caption = "Modéle 3, lnGDI_2019 ~ lngdpPercap_2007", - color = "Classe d'HDI") + - scale_color_discrete(name = "Classe d'HDI", labels = c("Haute", "Basse", "Moyenne", "Trés haute")) - - -### distances de Cook ---- -plot(mco4, which = 4) -### en ggplot frustre: -ggplot(mco4, aes(seq_along(.cooksd), .cooksd)) + - geom_col() -### effet intéressant quand on applique l'esthétiue par collage de la commande: -ggplot(fortify(mco4, gapmind_07_19_gdi), aes(seq_along(.cooksd), .cooksd)) + - geom_col(aes(color = HDI_Class)) # collage de color ! -# rectification par fill. -ggplot(fortify(mco4, gapmind_07_19_gdi), aes(seq_along(.cooksd), .cooksd)) + - geom_col(aes(fill = HDI_Class)) + # collage de color ! - geom_hline(color = "blue", linetype = 2, yintercept = 0.1) + - labs(title = "Graphique des distances de Cook", - subtitle = "Indicateur d'influence des observations", - x = "Index", y = "Distances de Cook", - caption = "Modéle 3, lnGDI_2019 ~ lngdpPercap_2007", - color = "Classe d'HDI") + # pourrait ajouter la palette Rcolorbrewer - scale_fill_discrete(name = "Continent", labels = c("Afrique", "Amérique", "Asie", "Europe", "Océanie")) - -# rectification par fill. -ggplot(fortify(mco4, gapmind_07_19_gdi), aes(seq_along(.cooksd), .cooksd)) + - geom_col(aes(fill = continent)) + # collage de color ! - geom_hline(color = "blue", linetype = 2, yintercept = 0.1) + - labs(title = "Graphique des distances de Cook", - subtitle = "Indicateur d'influence des observations", - x = "Index", y = "Distances de Cook", - caption = "Modéle 3, lnGDI_2019 ~ lngdpPercap_2007", - color = "Classe d'HDI") + # pourrait ajouter la palette Rcolorbrewer - scale_fill_discrete(name = "Classe d'HDI", labels = c("Haute", "Basse", "Moyenne", "Trés haute")) - - - -### Graphiques Résidus vs levier ---- -plot(mco4, which = 5) -### ggplot simple: -ggplot(mco4, aes(.hat, .stdresid)) + - geom_vline(size = 2, colour = "white", xintercept = 0) + - geom_hline(size = 2, colour = "white", yintercept = 0) + - geom_point() + geom_smooth(se = FALSE) -### ggplot amélioré: -ggplot(fortify(mco4, gapmind_07_19_gdi), aes(.hat, .stdresid)) + - geom_vline(size = 0.5, colour = "red", xintercept = 0) + - geom_hline(size = 0.5, colour = "red", yintercept = 0) + - geom_hline(size = 0.5, colour = "blue", yintercept = c(-2.5, 2.5), linetype = 2) + - geom_point(aes(color = HDI_Class)) + - geom_smooth(se = FALSE) + - labs(title = "Graphique des résidus vs leviers", - subtitle = "Indicateur d'influence des observations sur les résidus", - x = "Leviers", y = "Distances de Cook", - caption = "Modéle 3, lnGDI_2019 ~ lngdpPercap_2007", - color = "Classe d'HDI") + # pourrait ajouter la palette Rcolorbrewer - scale_color_discrete(name = "Classe d'HDI", - labels = c("Haute", "Basse", "Moyenne", "Trés haute")) -### on peut jouer sur la taille avec size dans geom point ! -ggplot(fortify(mco4, gapmind_07_19_gdi), aes(.hat, .stdresid)) + - geom_vline(size = 0.5, xintercept = 0) + - geom_hline(size = 0.5, yintercept = 0) + - geom_hline(size = 0.5, colour = "blue", yintercept = c(-2.5, 2.5), linetype = 2) + - geom_point(aes(color = HDI_Class, size = .cooksd)) + - geom_smooth(se = FALSE, size = 0.5) + - labs(title = "Graphique des résidus vs leviers", - subtitle = "Indicateur d'influence des observations sur les résidus", - x = "Leviers", y = "Résidus standardisés", - caption = "Modéle 3, lnGDI_2019 ~ lngdpPercap_2007", - color = "Classe d'HDI") + # pourrait ajouter la palette Rcolorbrewer - scale_color_discrete(name = "Classe d'HDI", - labels = c("Haute", "Basse", "Moyenne", "Trés haute")) - -### graphique Cook -- Leviers -plot(mco4, which = 6) # le sixiéme graphique de diagnostic ! -### ggplot basic -ggplot(mco4, aes(.hat, .cooksd)) + - geom_vline(xintercept = 0, colour = NA) + - geom_abline(slope = seq(0, 3, by = 0.5), colour = "white") + - geom_smooth(se = FALSE) + - geom_point() -### ggplot amélioré -ggplot(fortify(mco4, gapmind_07_19_gdi), aes(.hat, .cooksd)) + - geom_vline(xintercept = 0, colour = NA) + - geom_abline(slope = seq(0, 3, by = 0.5), colour = "red", linetype = 2) + # esthétiques de geom_line() - geom_smooth(se = FALSE) + - geom_point(aes(color = HDI_Class)) + - labs(title = "Graphique des leviers vs distances de Cook", - subtitle = "Levier = hii / (1 - hii)", - x = "Leviers", y = "Distances de Cook", - caption = "Modéle 3, lnGDI_2019 ~ lngdpPercap_2007", - color = "Classe d'HDI") + - scale_color_discrete(name = "Classe d'HDI", - labels = c("Haute", "Basse", "Moyenne", "Trés haute")) - -### on peut aussi modifier l'esthétique en faisant le ratio cook/hat: -ggplot(mco4, aes(.hat, .cooksd)) + - geom_point(aes(size = .cooksd / .hat)) + - scale_size_area() -# amélioré: -ggplot(fortify(mco4, gapmind_07_19_gdi), aes(.hat, .cooksd)) + - geom_vline(xintercept = 0, colour = NA) + - geom_abline(slope = seq(0, 3, by = 0.5), colour = "red", linetype = 2) + # esthétiques de geom_line() - geom_smooth(se = FALSE) + - geom_point(aes(color = HDI_Class, size = .cooksd / .hat)) + - scale_size_area() + - labs(title = "Graphique des leviers vs distances de Cook", - subtitle = "Levier = hii / (1 - hii)", - x = "Leviers", y = "Distances de Cook", - caption = "Modéle 3, lnGDI_2019 ~ lngdpPercap_2007", - color = "Classe d'HDI") + - scale_color_discrete(name = "Classe d'HDI", - labels = c("Haute", "Basse", "Moyenne", "Trés haute")) -smco4 - -### on voit donc la richesse des graphiques de diagnostic de régression ! - -#### regardons avec broom les mises en formes de modéles... ---- -install.packages("broom") -install.packages("broomhelpers") -install.packages("tidymodels") -install.packages("finalfit") -library(broom) -library(broom.helpers) -library(tidymodels) -library(finalfit) -(.packages()) -### https://broom.tidymodels.org/ -### https://www.tidymodels.org/ - -### la base: le modéle 3: -mco4 # le plus compact: l'objet associé au modéle... -summary(mco4) # un peu plus complet... mais... -# regardons le bazar: -str(mco4) - -### avec broom on transforme les modéles bazars en beaux tibbles ! -t.mco4 <- tidy(mco4) # ah c'est plus beau ! -t.mco4 -# noter la colonne terme accessible avec $ ! -aug.mco4 <- augment(mco4) # on a un équivalent élargi du modéle -g.mco4 <- glance(mco4) # coup d'oeil aux diagnostics de régression ! -### accéder aux objets modéle ---- -names(mco4) - -modele4 <- c(t.mco4, aug.mco4, g.mco4) -modele4 - -write.csv2(modele4, "modele4.csv") -write.csv2(t.mco4, "t.mco4.csv") -write.csv2(aug.mco4, "aug.mco4.csv") -saveRDS(t.mco4, "t.mco4.rds") - -#### Exporter des résultats... -modele.4 <- c(glance(mco4), tidy(mco4), augment(mco4)) -glimpse(modele.4) # on a le modéle complet avec les données. -View(modele.4) -modele.4 - -### explorer avec finalfit -# https://finalfit.org/reference/finalfit.html -library(finalfit) -gapmind_2007_19 %>% missing_glimpse() -### utilisation missing compare à partir de : -# https://finalfit.org/reference/missing_compare.html -dependent <- "Stadev" -explicatives <- c("lifeExp", "pop", "gdpPercap", "urban_pop_2019", "age_median_2019", "GDI_2019", "GDP_GUSDPPP_2017") -gapmind_2007_19 %>% finalfit(dependent, explanatory) -# multi(.data, dependent, explanatory, ...) -multi(.data, dependent, explanatory, ...) # ...Other arguments to pass to - -# https://cran.r-project.org/web/packages/broom.helpers/vignettes/tidy.html -ibrary(broom.helpers) -# https://larmarange.github.io/broom.helpers/ -library(gtsummary) - -### méthode 1: force brute par factomineR: -install.packages("FactoMineR") -library(FactoMineR) - -write.infile(modele.4, file = "modele.4.xls", sep="\t") - -### méthode 2: plus subtile, plusieurs modéles dans un classeur xlsx. -modele.2 <- c(glance(mco2), tidy(mco2), augment(mco2)) -write.infile(modele.2, file = "modele.2.xls", sep="\t") # comme en 1 -modele.3 <- c(glance(mco3), tidy(mco3), augment(mco3)) -write.infile(modele.3, file = "modele.3.xls", sep="\t") # comme en 1 -### avec le paquetage openxlsx beaucoup plus souple: -install.packages("openxlsx") -library(openxlsx) -diagajust.4 <- glance(mco4) -tidy4 <- tidy(mco4) -augm4 <- augment(mco4) -modeles.4.gdi <- createWorkbook(creator = "Formation R Cired/IEDES", - title = "Exemple d'exportation d'objets en xlsx", - subject = "Exportation des modéles estimés", - category = "Résultats d'estimations") -addWorksheet(modeles.4.gdi, "diagnostics ajustement") -addWorksheet(modeles.4.gdi, "tidy_modele") -addWorksheet(modeles.4.gdi, "augment_modele") -writeData(modeles.4.gdi, "diagnostics ajustement", diagajust.4) -writeData(modeles.4.gdi, "tidy_modele", tidy4) -writeData(modeles.4.gdi, "augment_modele", augm4) -saveWorkbook(modeles.4.gdi, file = "Modeles.4.gdi.estimes.xlsx") - -### méthode 3: méme paquetage commande write.xlsx: -write.xlsx(modele.2, "modele.2.xlsx") -write.xlsx(modele.3, "modele.3.xlsx") -write.xlsx(modele.4, "modele.4.xlsx") - -### méthode 4: bloc note markdown -write.table(t.mco4, "modele.4.txt", sep="\t") -t.mco4 -write.table(aug.mco4, "aug.mco4.txt", sep="\t") -aug.mco4 - -### exemple de compilation d'un script via appel de commande markdown -rmarkdown::render("Exemple_compilation_de_script.R", "pdf_document") - - -#### olsrr ---- -library(olsrr) -t.mco4 -aug.mco4 -summary(mco4) - -### ols_regress === ressemble à stata -ols_regress(log(GDI_2019) ~ log(gdpPercap), - weights = pop, - data = filter(gapmind_2007_19, !is.na(gapmind_2007_19$GDI_2019))) -### mais c'est du stata dans R !!! -mco4.stata <- ols_regress(log(GDI_2019) ~ log(gdpPercap), - weights = pop, - data = filter(gapmind_2007_19, !is.na(gapmind_2007_19$GDI_2019))) -mco4.stata -### nous pouvons utiliser les commandes olsrr -# https://olsrr.rsquaredacademy.com/ -ols_plot_resid_fit(mco4) -ols_plot_dfbetas(mco4) -ols_plot_resid_fit_spread(mco4) -ols_plot_resid_qq(mco4) -ols_test_normality(mco4) -ols_plot_resid_hist(mco4) -### tests d'hétéroscédasticité -ols_test_breusch_pagan(mco4) -ols_test_breusch_pagan(mco4, rhs = TRUE, multiple = TRUE) -ols_test_breusch_pagan(mco4, rhs = TRUE, multiple = TRUE, p.adj = 'sidak') -ols_test_score(mco4) -ols_test_f(mco4) -# mesures d'influence -ols_plot_cooksd_bar(model) -require(ggpacman) -library(ggpacman) -animate_pacman( - pacman = pacman, - ghosts = list(blinky, pinky, inky, clyde), - font_family = "xkcd") diff --git a/README.md b/README.md index 00c03f8..94bcf36 100644 --- a/README.md +++ b/README.md @@ -1,30 +1,11 @@ -# bricolR -Le séminaire R de la Cité du Développement Durable. -Ce séminaire est ouvert et de tous niveaux. On peut y présenter ses travaux en cours, résoudre des problèmes de code, présenter un paquetage qu'on l'on a trouvé utile et surtout partager des idées autour du langage R. -Ce répertoire met à disposition des personnes intéressées les scripts, markdown, quarto et données utilisées lors du séminaire. +Voici les documents quarto, codes et fichiers associés à la séance du séminaire R de la Cité du développement durable du 9 octobre 2025. -## séance du 27 juillet 2021 -tutoriels d'apprentissage de R. -Quelques liens utiles: +Le séminaire R de la Cité du Déeloppement Durable est un séminaire ouvert à toutes les personnes intéressées et organisé au Cired. -1) liste des fonctions entrant dans summarize: - - https://www.r-bloggers.com/2021/06/summarize-in-r-data-summarization-in-r/ - - https://dplyr.tidyverse.org/reference/summarise.html - - https://www.rdocumentation.org/packages/Hmisc/versions/4.5-0/topics/summarize -2) gestion de la mémoire: - - http://adv-r.had.co.nz/memory.html -3) remplacer des na pour les appels de fonctions smartEdA: - - https://tidyr.tidyverse.org/reference/replace_na.html -4) liens sur le package smartEdA: - - https://cran.r-project.org/web/packages/SmartEDA/vignettes/SmartEDA.html#example-for-case-2-target-variable-is-continuous - - https://cran.r-project.org/web/packages/SmartEDA/vignettes/CustomTable.html - - https://cran.r-project.org/web/packages/SmartEDA/vignettes/SmartTwoPlots.html - - https://cran.r-project.org/web/packages/SmartEDA/vignettes/SmartEDA.html -5) liens utiles pour progresser: - - https://finnstats.com/index.php/2021/05/25/how-to-find-dataset-differences-in-r/ - - https://finnstats.com/index.php/2021/04/02/tidyverse-in-r/ +contact : franck.nadaud@cnrs.fr -Complements: -- https://ggplot2-book.org/index.html -- pour ceux qui viennent de stata, il existe un package qui reproduit do by de stata: https://cran.r-project.org/web/packages/doBy/index.html -- un des meilleurs tutos ggplot du net: https://www.cedricscherer.com/2019/08/05/a-ggplot2-tutorial-for-beautiful-plotting-in-r/ +Here are the quarto, codes and files for the 9th october 2025 session of the R seminar of Cité du Développement Durable + +The R seminar is open to all interested persons with R and organized at Cired + +contact : franck.nadaud@cnrs.fr diff --git a/analyses_descriptives.R b/analyses_descriptives.R deleted file mode 100644 index 1d7cb6c..0000000 --- a/analyses_descriptives.R +++ /dev/null @@ -1,360 +0,0 @@ -############################################################################### -#### Analyses statistiques et exploratoires des donn?es gamind_2007_19 #### -############################################################################### - -### chargement des paquetages ---- -library(magrittr) # paquetage n?cessaire pour utiliser le tuyau ou pipe de programmation -library(gapminder) -library(tidyverse) -library(SmartEDA) -### d?finition du r?pertoire de travail ---- -setwd("D:/cours_R") -# https://thinkr.fr/debuter-avec-r-et-rstudio/ -#setwd("c:/Users/user/desktop/Cours_R") ### changez cela dans votre environnement -getwd() # afficher le r?pertoire de travail. -theme_set(theme_bw()) # pre-set the bw theme. - - -### on a un choix tr?s vaste de paquetages d'analyse. -# https://dabblingwithdata.wordpress.com/2018/01/02/my-favourite-r-package-for-summarising-data/ -# https://towardsdatascience.com/eda-in-r-with-smarteda-eae12f2c6094 - -### les r?sum?s classiques: ---- -# summary, fivenum, by(,summary) -summary(gapmind.2007.19[,"lifeExp"]) - - -summary(gapmind.2007.19$lifeExp) #notez la diff?rence avec la pr?c?dente commande - -summary(gapmind.2007.19) - -### on peut faire des r?sum?s selon les cat?gories d'un facteur -by(gapmind.2007.19, gapmind.2007.19$continent, summary) - -by(gapmind.2007.19, - list(gapmind.2007.19$continent, - gapmind.2007.19$HDI_Class), - summary) - -by(gapmind.2007.19, gapmind.2007.19$HDI_Class, summary) - -### on peut donc ?galement demander le r?sum? d'une seule variable: -by(gapmind.2007.19$lifeExp, gapmind.2007.19$continent, summary) -by(gapmind.2007.19$HDI_Class, gapmind.2007.19$continent, summary) -by(gapmind.2007.19[,"lifeExp"], gapmind.2007.19$continent, summary) -by(gapmind.2007.19[,"HDI_Class"], gapmind.2007.19$continent, summary) -### le dernier facteur, niveau de d?veloppement est peu pratique ? manier ! -# on peut le renommer pour l'utiliser: -gapmind.2007.19 <- rename(gapmind.2007.19, "Stadev" = "Developed / Developing Countries") -# attention ? la syntaxe: nouveau nom = ancien nom ! -# ne pas oublier l'affectation gapmind_2007_19 <- - -# https://dplyr.tidyverse.org/reference/rename.html - -# de m?me HDI_Class devrait ?tre red?fini en facteur: -gapmind.2007.19$HDI.Class <- as.factor(gapmind.2007.19$HDI_Class) # on maintenant un facteur - -by(gapmind.2007.19[,"HDI_Class"], gapmind.2007.19$Stadev, summary) -by(gapmind.2007.19[,"lifeExp"], gapmind.2007.19$Stadev, summary) - - -### via smart eda ---- -library(SmartEDA) # une suite de fonctions d'analyse descriptive pour le big data - -# https://www.rdocumentation.org/packages/SmartEDA/versions/0.3.8 -# https://github.com/daya6489/SmartEDA -# https://joss.theoj.org/papers/10.21105/joss.01509 - - -# Overview of the data - Type = 1 -ExpData(data = gapmind.2007.19, type = 1) # r?sum? g?n?ral des donn?es - -# Structure of the data - Type = 2 -ExpData(data = gapmind.2007.19, type = 2) # r?sum? plus d?taill? - -### r?sum?s des variables ----- -### ajouter exporter fichiers pour voir ! -# statistiques sur les variables num?riques -ExpNumStat(gapmind.2007.19, - by = "A", # r?sum? statistique pour toutes les variables Group = all - gp = NULL, # pas de variables pr?cis?e - Qnt = seq(0,1, 0.1), # quantiles ici d?ciles - MesofShape = 2, # mesures de forme == sym?trie et applatissement - Outlier = TRUE, # calcul des pivots de box plot et outresitu?s - round = 2, # arrondi ? deux d?cimales - Nlim = 10) # limite de valeurs num?riques diff?rentes -# mais on peut calculer selon un facteur: -ExpNumStat(gapmind.2007.19, - by = "G", # r?sum? statistique par Groupe - gp = "continent", # facteur = continent - Qnt = seq(0, 1, 0.1), # quantiles ici d?ciles - MesofShape = 2, # mesures de forme == sym?trie et applatissement - Outlier = TRUE, # calcul des pivots de box plot et outresitu?s - round = 2, # arrondi ? deux d?cimales - Nlim = 10) # limite de valeurs num?riques diff?rentes -# et on peut m?me faire les deux: par une variable et globalement: -ExpNumStat(gapmind.2007.19, - by = "GA", # r?sum? statistique pour toutes les variables Group + All - gp = "HDI_Class", # facteur == HDI_Class - Qnt = seq(0,1, 0.1), # quantiles ici quartiles 1 et 3 - MesofShape = 2, # mesures de forme == sym?trie et applatissement - Outlier = TRUE, # calcul des pivots de box plot et outresitu?s - round = 2, # arrondi ? deux d?cimales - Nlim = 10) # limite de valeurs num?riques diff?rentes -# En fait il faudrait enlever les NA en amont de la commande... - - -# statistiques des fr?quences sur les facteurs -ExpCTable(gapmind.2007.19, - Target = NULL, - margin = 1, - clim = 10, - nlim = 3, - round = 2, - bin = NULL, - per = T) # resultats en % des cat?gories du facteur per = TRUE -# l? aussi on peut choisir un facteur qui sera crois? avec les deux autres -# continent crois? avec hdi et stadev: -ExpCTable(gapmind.2007.19, Target = "continent", margin = 1, clim = 10, nlim = 3, round = 2, per = F) -# continent crois? avec hdi et stadev totaux en pourcentage colonne: -ExpCTable(gapmind.2007.19, Target = "continent", margin = 1, clim = 10, nlim = 3, round = 2, per = T) -# HDI_Class crois? avec hdi et stadev en % colonne: -ExpCTable(gapmind.2007.19, Target = "HDI_Class", margin = 1, clim = 10, nlim = 3, round = 2, per = T) -# HDI_Class crois? avec hdi et stadev en % ligne (margin = 2): -ExpCTable(gapmind.2007.19, Target = "HDI_Class", margin = 2, clim = 10, nlim = 3, round = 2, per = T) - - -### une analyse du degr? d'association des variables ? chaque facteur: -catstat <- ExpCatStat(gapmind.2007.19, Target = "continent", result = "Stat", clim = 10, nlim = 10) -class(catstat) - -# idem avec result = IV (information value) -ExpCatStat(gapmind.2007.19, Target = "continent", result = "IV", clim = 10, nlim = 10) -# de mani?re int?ressante il a red?coup? toutes les variables continues en classes ! -# de toute ?vidence, les autres variables n'ont pas de pouvoir pr?dictif de continent... - -### changeons de variables cible: -ExpCatStat(gapmind.2007.19, Target = "HDI_Class", result = "Stat", clim = 10, nlim = 10) -ExpCatStat(gapmind.2007.19, Target = "Stadev", result = "Stat", clim = 10, nlim = 10) - -### probl?me ! SmartEDA semble ne pas aimer les NAs ! -summary(gapmind.2007.19) -# on pourrait filter la base de travail pour retirer les valeurs manquantes: -gapmind.07.19.hdi <- filter(gapmind.2007.19, !is.na(gapmind.2007.19$HDI_Class)) # noter ! - -glimpse(gapmind.07.19.hdi) -summary(gapmind.07.19.hdi) -str(gapmind.07.19.hdi) - -## exemple replace_na() : https://tidyr.tidyverse.org/reference/replace_na.html -(df <- tibble(x = c(1, 2, NA), y = c("a", NA, "b"))) -(df %>% replace_na(list(x = 0, y = "unknown"))) - -gapmind.na.omit <- na.omit(gapmind.2007.19) -summary(gapmind.na.omit) # gapmind sans aucune donnée manquante. - -gapmind.2007.19.replace_na <- gapmind.2007.19 -summary(gapmind.07.19.hdi$Stadev) - -gapmind.07.19.hdi %>% - mutate(Stadev = replace_na(Stadev, "missing")) -summary(gapmind.07.19.hdi$Stadev) - -gapmind.2007.19$Stadev <- replace_na("missing") -gapmind.2007.19$Stadev -View(gapmind.2007.19) - -### différences d'objets listes et vecteurs. -# un vecteur numérique: -v <- c(2, 4, 3.2, 5.9, 6.0001) -v -class(v) -mode(v) - -(3*v) - -(w <- c(2, 6, TRUE, "Alice", NA)) -class(w) - -(z <- c(2, 6, TRUE, 1e6, NA)) -class(z) - -(list.1 <- list(4, 6, TRUE, "Alice", NA)) - -class(gapmind.2007.19$Stadev) -mode(gapmind.2007.19$Stadev) -summary(gapmind.2007.19$Stadev) - -by(gapmind.07.19.hdi, gapmind.07.19.hdi$HDI.Class, summary) - -# on retir? les NA dans le facteur hdi.class: -ExpCatStat(gapmind.07.19.hdi, Target = "HDI.Class", result = "Stat", clim = 10, nlim = 10) -# cela devient plus convaincant et int?ressant ! -ExpCatStat(gapmind.07.19.hdi, Target = "HDI.Class", result = "IV", bins = 5, clim = 5, nlim = 5) -ExpCatStat(gapmind.07.19.hdi, Target = "HDI.Class", result = "IV", Pclass = 2, bins = 5, clim = 5, nlim = 5) - -summary(gapmind.07.19.hdi$HDI.Class) - -### r?sum?s statistiques des variables quantitatives avec ExpNumStat -hdi.exp.num <- ExpNumStat(gapmind.07.19.hdi, - by = "A", # r?sum? statistique pour toutes les variables Group = all - gp = "GDI_2019", # pas de variables pr?cis?e - Qnt = seq(0,1,0.1), # quantiles ici d?ciles - MesofShape = 2, # mesures de forme == sym?trie et applatissement - Outlier = TRUE, # calcul des pivots de box plot et outresitu?s - round = 2, # arrondi ? deux d?cimales - Nlim = 10) # limite de valeurs num?riques diff?rentes -View(hdi.exp.num) -### lorsque la variable cible est continue, il calcule des corr?lations -gapmind.07.19.gdi <- filter(gapmind.2007.19, !is.na(gapmind.2007.19$GDI_2019)) - -gapmind.07.19.na <- filter(gapmind.2007.19, is.na(gapmind.2007.19$GDI_2019)) - -summary(gapmind.07.19.gdi$GDI_2019) -summary(gapmind.07.19.na) -#changement du nom de Stadev -rename(gapmind.07.19.gdi, "Stadev" = "Developed / Developing Countries") -rename(gapmind.07.19.na, "Stadev" = "Developed / Developing Countries") - -by(gapmind.07.19.na, gapmind.07.19.na$continent, summary) -by(gapmind.07.19.na, gapmind.07.19.na$HDI_Class, summary) - -ExpNumStat(gapmind.07.19.gdi, - by = "A", # r?sum? statistique pour toutes les variables Group = all - gp = "GDI_2019", # pas de variables pr?cis?e - Qnt = seq(0,1,0.1), # quantiles ici d?ciles - MesofShape = 2, # mesures de forme == sym?trie et applatissement - Outlier = TRUE, # calcul des pivots de box plot et outresitu?s - round = 2, # arrondi ? deux d?cimales - Nlim = 10) # limite de valeurs num?riques diff?rentes -### il faut donc retirer les NAs pour obtenir des r?sultats probants - - -# Remarquez les corr?latons finales sont NA pour les variables comptant des NA ==> -# le plus direct serait de retirer tous les NA... -# rm(gampind_07_19_nona) - -gapmind.07.19.nona <- na.omit(gapmind.2007.19) # sauf que nous perdons 32 pays sur 142 ! - -32/142 # soit 23% ! - -summary(gapmind.07.19.nona) - -# reprenons -ExpData(data = gapmind.07.19.nona, type = 1) # on voit qu'il n'y a plus de NA -ExpData(data = gapmind.07.19.nona, type = 2) # on voit qu'il n'y a plus de NA - -### résumé de type A avec comme variable cible == GDI_2019 -cor.GDI.2019 <- ExpNumStat(gapmind.07.19.nona, - by = "A", # r?sum? statistique pour toutes les variables Group = all - gp = "GDI_2019", # pas de variables pr?cis?e - Qnt = seq(0,1,0.1), # quantiles ici d?ciles - MesofShape = 2, # mesures de forme == sym?trie et applatissement - Outlier = TRUE, # calcul des pivots de box plot et outresitu?s - round = 2, # arrondi ? deux d?cimales - Nlim = 10) -# on note la correlation n?gative avec l'indice d'in?galit?s de genre et nulle avec le pib ! -(ExpNumStat(gapmind.07.19.nona, - by = "A", # r?sum? statistique pour toutes les variables Group = all - gp = "GNI_2019", # pas de variables pr?cis?e - Qnt = seq(0,1,0.1), # quantiles ici d?ciles - MesofShape = 2, # mesures de forme == sym?trie et applatissement - Outlier = TRUE, # calcul des pivots de box plot et outresitu?s - round = 2, # arrondi ? deux d?cimales - Nlim = 10)) - -(ExpNumStat(gapmind.07.19.nona, -by = "A", # r?sum? statistique pour toutes les variables Group = all -gp = "Gender_Inequality_2019", # pas de variables pr?cis?e -Qnt = seq(0,1,0.1), # quantiles ici d?ciles -MesofShape = 2, # mesures de forme == sym?trie et applatissement -Outlier = TRUE, # calcul des pivots de box plot et outresitu?s -round = 2, # arrondi ? deux d?cimales -Nlim = 10)) - -### Calculs de coefficients d'applatissment: -ExpKurtosis(gapmind.2007.19$GDI_2019, type = "moment") -ExpKurtosis(gapmind.2007.19$GDI_2019, type = "excess")# kurtosis = moment de degr? 4 -ExpKurtosis(gapmind.2007.19$gdpPercap, type = "excess") # moment - 4 - -### exploration d'outresitu?s: -boxout.gapmind <- ExpOutliers(gapmind.2007.19, - varlist = c("GDI_2019", "gdpPercap", "lifeExp", "Gender_Inequality_2019"), - method = 'Boxplot', - capping = c(0.05, 0.95)) # d?finitions du boxplot -View(boxout.gapmind) -boxout.gapmind - -stdout.gapmind <- ExpOutliers(gapmind.2007.19, - varlist = c("GDI_2019", "gdpPercap", "lifeExp", "Gender_Inequality_2019"), - method = '2xStDev', - capping = c(0.05, 0.95)) # d?finition de nombre d'?carts-types -stdout.gapmind -str(stdout.gapmind) -class(stdout.gapmind) -mode(stdout.gapmind) - -stdout.gapmind$outlier.index$lower.out.index$lifeExp -stdout.gapmind$outlier.index$upper.out.index - -### ExpReport ==> cr?er rapport avec markdown ---- -### ExpReport -install.packages("markdown") -library(markdown) -### rapport sur la base compl?te ! -ExpReport(gapmind.2007.19, op_file = "rapport.gapminder.html") -# idem mais avec une variable continue cible : GDI_2019 -ExpReport(gapmind.2007.19, Target = "GDI_2019", op_file = "rapp.GDI_2019.html") -# idem avec facteur : HDI_Class -ExpReport(gapmind_2007_19, Target = "Stadev", theme = "stata", op_file = "rapp.stadev.html") - -# exploration de donn?es manquantes: -# https://cran.r-project.org/web/packages/finalfit/index.html -# https://cran.r-project.org/web/packages/finalfit/vignettes/missing.html -install.packages("finalfit") -install.packages("visdat") -# paquetage naniar -# https://cran.r-project.org/web/packages/naniar/index.html -# https://cran.r-project.org/web/packages/naniar/vignettes/getting-started-w-naniar.html -# https://cran.r-project.org/web/views/MissingData.html -# https://cran.r-project.org/web/views/MissingData.html#exploration -# https://cran.r-project.org/web/views/MissingData.html -# -library(naniar) -library(visdat) -library(finalfit) -(.packages()) - -gapmind.2007.19 %>% - missing_plot() - -explanatory <- c("gdpPercap", "urban_pop_2019", "lifeExp", "age_median_2019") -dependent <- "GDI_2019" - -gapmind.2007.19 %>% - missing_pattern(dependent, explanatory) - -comb <- c(gapmind.2007.19, boxout.gapmind) -comb - -View(comb) -gapmind.data <- as.data.frame(comb[1:17]) -class(gapmind.data) -View(gapmind.data) - - -comb$continent -glimpse(comb) - - - -class(comb) -mode(comb) -str(comb) - -library(visdat) -vis_dat(gapmind.2007.19) -gapmindat <- gapminder -vis_dat(gapmindat) -vis_dat(UNSD_Regions) - diff --git a/bricolageR.R b/bricolageR.R deleted file mode 100644 index 3d3ee88..0000000 --- a/bricolageR.R +++ /dev/null @@ -1,242 +0,0 @@ -######## premier script exemple de script -# juste p?ur voir... - -#### section 1 ----- - - -# c'est du commentaire - -#### section 2 ---- - - -### chargement des paquetages ---- -library(magrittr) # paquetage n?cessaire pour utiliser le tuyau ou pipe de programmation -library(gapminder) -library(tidyverse) -install.packages("gapminder") -install.packages("data.table") - -(.packages()) - -### d?finition du r?pertoire de travail ---- -setwd("D:/cours_R") -setwd("c:/Users/user/desktop/Cours_R") ### changez cela dans votre environnement -getwd() # afficher le r?pertoire de travail. -theme_set(theme_bw()) # pre-set the bw theme. - -theme_set(theme_bw()) -theme_get() - -# afficher les paquetages charg?s -(.packages()) # noter le . qui est une variable d'environnement R -# afficher tous les paquetages (notez la diff?rence) -library() -(.Rdata) - - -### premiers pas avec gapminder ---- -# un extrait des wdi de la banque mondiale: https://www.gapminder.org/data/ -? gapminder -? library -str(gapminder) # examiner la structure d'un objet R arbitraire -class(gapminder) -? tibble -mode(gapminder) - -head(gapminder) # visualiser les quelques premi?res lignes d'un cadre de donn?es -tail(gapminder) # on peut regarder les derni?res lignes par tail(df) -head(gapminder, 20) # visualiser les 20 premi?res lignes d'un cadre de donn?es -tail(gapminder, 20) # les vingt derni?res lignes -head(gapminder, -6L) # on n?glige les six derni?res lignes -head(gapminder, n = c(20, 2)) # on peut visualiser des blocs en pr?cisant par un vecteur -# ici c(20,2) -tail(gapminder, n = c(20, -2)) # en pr?cisant -2 dans le vecteur, la fonction comprend -# qu'il faut n?gliger les deux premi?res colonnes mais cela nous g?ne un peu ici: - -# pour des ?l?ments sur l'indexation des R, voir: -# # http://www.cookbook-r.com/Basics/Indexing_into_a_data_structure/ - -### fonction glimpse (aper?u) -glimpse(gapminder) # glimpse == aper?u des donn?es ! Noter la transposition comme dans str() -glimpse(gapminder::continent_colors) # une variable du paquetage gapminder -View(gapminder) # ouvrir la visionneuse de donn?es -### c'est done un panel de s?ries temporelles par pays dans l'ordre alphab?tique -?View -View(gapminder) -glimpse(gapminder$pop) - -### synth?se des donn?es ----- -### premiers r?sum?s: -summary(gapminder) # r?sum?s de base - -class(gapminder$continent) -mode(gapminder$continent) -table(gapminder$continent) # continent == d?coupage ONU -table(gapminder$year) -table(gapminder$country) - - -### creation d'un objet tableau r?sumant les donn?es par continent pour 2007 -continent <- gapminder %>% - filter(year == 2007) %>% - group_by(continent) %>% - summarize(lifeExp = median(lifeExp)) -continent -View(continent) -str(continent) - -## variance de l'espérance de vie -continent.V.LE <- gapminder %>% - filter(year == 2007) %>% - group_by(continent) %>% - summarize(lifeExp = var(lifeExp)) -continent.V.LE - -### on peut regrouper selon l'ann?e et le continent: -#library(magrittr) -(.packages()) - -continent.yr <- gapminder %>% - group_by(year, continent) %>% - summarize(lifeExp = median(lifeExp)) -continent.yr -str(continent.yr) # il est en format long mais cela pourra ?tre utile pour les graphiques - -### resum? inverse: -continent.ct <- gapminder %>% - group_by(continent, year) %>% - summarize(lifeExp = median(lifeExp)) -continent.ct -str(continent.ct) - -### on peut aussi grouper plusieurs r?sum?s: -continent.median <- gapminder %>% - filter(year == 2007) %>% - group_by(continent) %>% - summarize(lifeExp = median(lifeExp), - gdp_pc = median(gdpPercap), - pop = median(pop), - countries = n()) # il suffit donc de pr?ciser les r?sum?s voulus -continent.median -str(continent.median) - -### on finit sur le resum? m?dian en format long avec ann?es et 4 indicateurs -continent.median.ct <- gapminder %>% - group_by(continent, year) %>% - summarize(lifeExp = median(lifeExp), - gdp.pc = median(gdpPercap), - pop = median(pop), - countries = n()) # il suffit donc de pr?ciser les r?sum?s voulus -continent.median.ct -str(continent.median.ct)# structure plus complexe du tibble -summary(continent.median.ct) - - - - - -### comment ensuite joindre gapminder avec les indicateurs de genr?s de l'ONU -(gapmind.2007 <- gapminder %>% - filter(year == 2007)) - -gapmind.2007 -head(gapmind.2007, 20) -glimpse(gapmind.2007) -str(gapmind.2007) # tout est ok ! -glimpse(gapmind.2007) - -### importation des indicateurs du d?veloppement humain ONU - -# http://hdr.undp.org/en/content/download-data - -#rm(ONU_HDI) -View(ONU_HDI) -head(ONU_HDI) -glimpse(ONU_HDI) -str(ONU_HDI) -summary(ONU_HDI) -### nous voici tr?s embarass?s: les variables sont cod?es en caract?res ! -# que s'est-il pass? ? l'importation ? -# Rstudio a consid?r? les variables avec des caract?res textes comme textes ! -# les caract?res ".." ne sont pas conformes dans R. Ce sont des donn?es manquantes -#on les remplace par une valeur valide: NA. -install.packages("naniar") -(R.version) -library(naniar) -# https://cran.r-project.org/web/packages/naniar/vignettes/replace-with-na.html -ONU_HDI %>% replace_with_na_all(condition = ~. == "..") -str(ONU_HDI) -str(gapmind.2007) -summary(ONU_HDI) -### nous allons, changer les caract?ristiques des colonnes du tibble ONU_HDI -ONU_HDI$Country <- as.factor(ONU_HDI$Country) -ONU_HDI$HDI_Class <- as.factor(ONU_HDI$HDI_Class) -ONU_HDI$Rang_HDI_2019 <- as.numeric(ONU_HDI$Rang_HDI_2019) -ONU_HDI$age_median_2019 <- as.numeric(ONU_HDI$age_median_2019) -ONU_HDI$Gender_Inequality_2019 <- as.numeric(ONU_HDI$Gender_Inequality_2019) -ONU_HDI$GDI_2019 <- as.numeric(ONU_HDI$GDI_2019) -ONU_HDI$GDI_Group_2019 <- as.numeric(ONU_HDI$GDI_Group_2019) -ONU_HDI$GNI_2019 <- as.numeric(ONU_HDI$GNI_2019) -ONU_HDI$GDP_GUSDPPP_2017 <- as.numeric(ONU_HDI$GDP_GUSDPPP_2017) - - -### En fait on peut importer correctement tout cela avec readxl -# recommen?ons -View(ONU_HDI) -head(ONU_HDI) -glimpse(ONU_HDI) -str(ONU_HDI) -summary(ONU_HDI) -# tout est ok sauf les deux premi?res colonnes qui sont en caract?res... -#https://cran.r-project.org/web/packages/WDI/index.html - -### fichiers ONU r?gions: -# https://unstats.un.org/unsd/methodology/m49/overview/ -View(UNSD_Regions) -head(UNSD_Regions) -glimpse(UNSD_Regions) -str(UNSD_Regions) -summary(UNSD_Regions) -(.packages()) -### on apparie les bases ONU_HDI et UNSD_Regions -# tout d'abord on vire les huit premi?res colonnes de UNSD_Regions -UNSD_Regions <- select(UNSD_Regions, -c(1:8)) # force brute mais ?a marche! -write.csv2(UNSD_Regions, "UNSD_Regions.csv") -# on fait ensuite la jointure ? gauche de - -# https://dplyr.tidyverse.org/reference/mutate-joins.html - -ONU <- left_join(ONU_HDI, UNSD_Regions, by = c("Country" = "Country or Area")) -View(ONU) -head(ONU, 20) -glimpse(ONU) -str(ONU) -# tout a parfaitement march? et on peut donc faire une jointure gauche sur ONU -summary(ONU) # avant cela on va se d?barasser des colonnes 13--17 -ONU <- select(ONU, -c(13:17)) # attention ! bien distinguer c(13,17) de c(13:17) -glimpse(ONU) -ONU <- select(ONU, -c(12)) -# on transforme la derni?re colonne en facteur: -ONU$`Developed / Developing Countries` <- as.factor(ONU$`Developed / Developing Countries`) - - -### on peut maintenant op?rer la jointure ? gauche sur gapminder_2007: -gapmind.2007.19 <- left_join(gapmind.2007, ONU, by = c("country" = "Country")) -View(gapmind.2007.19) -head(gapmind.2007.19, 20) -tail(gapmind.2007.19, 25) -glimpse(gapmind.2007.19) -str(gapmind.2007.19) -summary(gapmind.2007.19) -str(ONU) - -gapmind.2007.19$HDI_Class <- as.factor(gapmind.2007.19$HDI_Class) -(.packages()) -### exercices: -# 1. construire un r?sum? de gapmind_2007_19 regroup? par : continents, classes d'hdi et niveau de developpement -# 2. examiner la jointure ? droite et compl?te de gapmind_2007 avec ONU : que constatez vous ? -# 3. sur la modification de ONU tester la difference entre c(13,17) et c(13:17) comment corrigeriez-vous ? -# 4. trouver quelques questions. - -#changement du nom de Stadev -rename(gapmind.2007.19, "Stadev" = "Developed / Developing Countries") diff --git a/bricoleR_2025.6_tests_statistiques.qmd b/bricoleR_2025.6_tests_statistiques.qmd new file mode 100644 index 0000000..fbd994a --- /dev/null +++ b/bricoleR_2025.6_tests_statistiques.qmd @@ -0,0 +1,537 @@ +--- +title: "Bricole'R 2025.6 tests sous R" +author: "Francky" +html_document: + code_folding: hide + theme: readable + highlight: zenburn + toc: true + toc_depth: 2 + numbered_section: true + fig_width: 13 + fig_height: 8 + fig_caption: true + df_print: paged +editor: visual +--- + +## Introduction + +Ce document quarto regroupe les tests dans R à partir de la formation des 22 au 24 septembre 2025. + +**Avertissement** : + +Les niveaux de R étaient très hétérogènes lors de cette formation qui s'est plutôt axée sur la théorie et la pratique dans divers environnements essentiellement jasp, excel et finalement R. + +Par contre, le supports powerpoint de la formation sont pratiquement tous en R et complètent les fichiers excel divers associés. Le support de cours est très riche : il fait presque 300 pages. + +## Test de Student + +On s'attaque ici au test de student. + +t-test : il existe deux protocoles : + +- données indépendantes == pas les mêmes individus + +- données appariées == mêmes individus appariés + +Deux scénarios très différents ! + +- En données indépendantes :==\> on s'intéresse à la **différences des moyenne**! + +- En données appariées ==\> on s'intéresse on à la **moyenne des différences** + +**Par défaut il ne faut pas préciser en données indépendantes**. + +exemple dans xl sur données 2 materiaux.xlsx : fonction t.test 1 = observations pairées (appariées : erreur de traduction microsoft !). + +Package esquisse : + +[esquisse](https://dreamrs.github.io/esquisse/) + +Un wrapper de ggplot avec interface graphique et récupération du code pour script / quarto + +[glossaire ISI](https://isi-web.org/glossary/1355) paramètre de localisation == différence des moyennes ! + +JASP calcule l'intervalle de confiance de la différence des moyennes ! + +[site jasp](https://jasp-stats.org/thank-you-for-downloading-jasp-win64/) + +[extension graphpad dans R](https://csdaw.github.io/ggprism/) + +### test de Student simple + +```{r, test de student avec collage} +Data2M <- coller() # avec coller +str(Data2M) # il les colle en caractères ! +Data2M$INOX <- as.numeric(Data2M$INOX) +Data2M$ALU <- as.numeric(Data2M$ALU) +summary(Data2M) +# test de student ALU et INOX : différence des moyennes +t.test(Data2M$INOX, Data2M$ALU) +# Notez que R fait automatiquement la correction de Welsh +t.test(Data2M$INOX, Data2M$ALU, var.equal = TRUE) +# test T en données appariées : moyennes des différences +t.test(Data2M$INOX, Data2M$ALU, var.equal = TRUE, paired = TRUE) +test_t <- t.test(Data2M$INOX, Data2M$ALU, var.equal = TRUE, paired = TRUE) +(test_t) +class(test_t) +str(test_t) +attributes(test_t) <- "test machine 1" +``` + +Faisons le test en important les données et en testant une variété d'options. + +La commande t.test est très riche car elle créée une liste de résultats exploitables par la suite. + +```{r, test de Student avec import et options} +Data2M <- readRDS("Data2M.rds") # importation d'un rds +str(Data2M) # cette fois c'est du numérique +summary(Data2M) # on a donc deux variables numériques INOX et ALU + +# Créons un objet t-test : +resist.na <- t.test(Data2M) # na pour non apparié +(resist.na) +str(resist.na) +# qu'est-ce qu'il a fait ? La moyenne de l'ensemble des données ! + +## On peut tester sur la moyenne d'une ou deux variables. + +## test univarié : on teste l'égalité à une valeur sur ALU +# on peut tester l'égalité à une moyenne sur une valeur connue pour une variable +resist.alu <- t.test(Data2M$ALU) # valeurs par défaut +(resist.alu) +# par défaut il teste la positivité d'une moyenne : xbar > 0 + +# on peut tester l'égalité à une valeur de référence : tolérance, norme, population... +resist.alu <- t.test(Data2M$ALU, + mu = 65, + alternative = "less", + conf.level = 0.99) +(resist.alu) # moyenne < 65 + +resist.alu <- t.test(Data2M$ALU, + mu = 65, + alternative = "greater", + conf.level = 0.99) +(resist.alu) # moyenne > 65 + +resist.alu <- t.test(Data2M$ALU, + mu = 65, + conf.level = 0.99) +(resist.alu) # moyenne centrée sur 65 + + +# tests sur deux variables : moyenne INOX = ALU +resist.na <- t.test(Data2M$INOX, Data2M$ALU) +(resist.na) + +# on pourrait tester plus strictrement : 99% +resist.na <- t.test(Data2M$INOX, Data2M$ALU, conf.level = 0.99) +str(resist.na) +class(resist.na) +(resist.na) + +# test de moyenne INOX < ALU +resist.na <- t.test(Data2M$INOX, Data2M$ALU, + alternative = "less", conf.level = 0.99) +(resist.na) + +# test de moyenne INOX > ALU +resist.na <- t.test(Data2M$INOX, Data2M$ALU, + alternative = "greater", conf.level = 0.99) +(resist.na) + + +# On peut tester inférieure à une valeur de référence : mu = 65 +resist.na <- t.test(Data2M$INOX, Data2M$ALU, + mu = 65, + alternative = "less", + conf.level = 0.99) +(resist.na) + + +# on pourrait aussi tester de manière appariée +resist.ap <- t.test(Data2M$INOX, Data2M$ALU, paired = TRUE) # ap : apparié +(resist.ap) + +resist.ap <- t.test(Data2M$INOX, Data2M$ALU, + paired = TRUE, + conf.level = 0.99) # ap : apparié +(resist.ap) +``` + +### Le paquetage Rstatix + +On peut aussi faire appel au paquetage rstatix : + +```{r, avec rstatix} +library(rstatix) +DM <- readRDS("DM.rds") +summary(DM) +# utiliser t_test de rstatix +t_test(DM, Y ~ Materiau) +DM %>% t_test(Y ~ Materiau) +# transformons Materiau en facteur : +library(tidyverse) +DM <- mutate_if(DM, is.character, as.factor) # le plus radical +DM$Materiau <- as.factor(DM$Materiau) # voie base R +summary(DM) +tests_materiaux <- t_test(DM, Y ~ Materiau) +View(tests_materiaux) +# les teste toutes les combinaisons de tests sur le facteur Materiau + +# On peut fixer les comparaisons, +tests_materiaux <- t_test(DM, Y ~ Materiau, + comparisons = list(c("Aluminium", "Inox"), + c("Acier", "Cuivre"))) +View(tests_materiaux) +# On peut définir un groupe de référence : +tests_materiaux <- t_test(DM, Y ~ Materiau, ref.group = "Acier") +View(tests_materiaux) # Il compare Acier aux autres métaux + +# corrections multiples = comme on fait des comparaisons multiples il faut corriger la pvalue +tests_materiaux <- t_test(DM, Y ~ Materiau, p.adjust.method = "bonferroni") +View(tests_materiaux) # avec la correction de Bonferroni == alpha / Nb tests + +tests_materiaux_fdr <- t_test(DM, Y ~ Materiau, p.adjust.method = "fdr") +View(tests_materiaux_fdr) # avec la correction de Bonferroni == alpha / Nb tests + +tests_materiaux_fdr <- t_test(DM, Y ~ Materiau, + p.adjust.method = "fdr", + detailed = TRUE) # avec résultats complets +View(tests_materiaux) +``` + +Rstatix gère les configurations sans problème au contraire de t.test qui lui n'admet que des facteurs à deux modalités. Pour plus de deux modalités il faut passer en analyse de variance en base R. + +```{r, test t avec comparaison colonnes} +resist <- coller() +summary(resist) +resist$Metal <- as.factor(resist$Metal) +resist$Resistance <- as.numeric(resist$Resistance) +summary(resist) +t.test(data = resist, Resistance ~ Metal) # bien préciser les options +# on retrouve les valeurs vues plus haut, à vous de jouer sur les options ! +``` + +On test l'analyse de variance à un facteur + +```{r, anova à un facteur} +# readRDS("DM.rds") +# on emploie ici la méthode anova directement sur les données +ModeleAnova1 <- aov (data = DM, Y ~ Materiau) +ResumeAnova1 <- summary (ModeleAnova1) +plot(ModeleAnova1, 1:6) +summary(ModeleAnova1) +names (ModeleAnova1) # accès aux objets de l'Anova +(ResumeAnova1) +ResumeAnova1 [[1]] [5] # accès à la p-value +ModeleAnova1 $ residuals # accès aux résidus +shapiro.test ( ModeleAnova1 $ residuals ) # Normalité des résidus +plot(ModeleAnova1 $ residuals) +(ModeleAnova1$fitted.values) +(ModeleAnova1$residuals) +plot(ModeleAnova1,1:6) + +TukeyHSD (ModeleAnova1) # Test de Tukey Post Hoc de base sur modèle aov +plot(TukeyHSD(ModeleAnova1, "Materiau")) # graphe des intervalles de confiance +print(TukeyHSD(ModeleAnova1)) # méthode print spécifique + +# Tests de Tukey avancé +# Nécessite la library (multcomp) et variable facteur en Factor +library (multcomp) +res.lm = lm (data = DM, Y ~ Materiau) +summary(res.lm) +T.Tukey = glht (ModeleAnova1, linfct = mcp ( Materiau = "Tukey" )) +summary (T.Tukey) +cld (T.Tukey) # Formation des groups de modalités avec lettres (a,b,c,…) +plot (T.Tukey) # Graphes des IC des differences des moyennes + +``` + +Un guide conçis sur l'utilisation de aov() et anova() dans R : + +[guide anova](https://www.geeksforgeeks.org/r-language/when-to-use-aov-vs-anova-in-r/) + +[un chapitre sur l'anova](https://bookdown.org/steve_midway/DAR/understanding-anova-in-r.html) + +En résumé : aov() pour tester les données, anova() pour tester des modèles lm(), glm()... + +Le paquetage multcomp : + +[paquetage multcomp](https://cran.r-project.org/web/packages/multcomp/refman/multcomp.html) + +Comparaison multiples dans des contextes de modèles linéaires. + +## Le test du khi² + +La commande `chisq.test` attend des vecteurs sous forme de facteurs croisés dont elle compte les occurances par croisements de modalités. + +C'est un test d'indépendance par comptage de croisements de modalités. + +On peut par contre importer directement une table de contingence selon divers formats mais avec quelques remarques. + +#### cas 1 : tableau de données de classe table + +On utilise la commande `table` ou `as.table` pour créer un tableau R dont on précise les en-têtes avec la commande `dimnames`, comme dans l'aide de `chisq.test`. + +#### cas 2 : + +On importe une table de contingence en format large. Dans les options d'importation XL il faut préciser `rowNames = TRUE et colNames = TRUE.` + +#### cas 3 : + +Une liste de deux vecteurs avec les modalités répétées autant de fois au croisements. La commande va reconstruire par comptage la table de contingence à partir des modalités rencontrées des facteurs. + +#### cas 4 : + +On importe une table en format long et on la déploie avec pivot_wider ou spread ou un équivalent. + +```{r, test du khi 2 avec diverses données} +### Cas 1 : tableau de données de classe table +require(tidyverse) +Maladies <- as.table(rbind(c(28, 9, 29, 5), + c(73, 12, 25, 9), + c(29, 18, 13, 5), + c(50, 14, 20, 8))) +dimnames(Maladies) <- list( + Maladie = c("Rougeole", "Varicelle", "Grippe", "Scarlatine"), + Région = c("Languedoc", "Alsace", "Auvergne", "Bretagne")) +str(Maladies) +(Maladies) +class(Maladies) +# test du khi² sur le tableau construit +chisq.test(Maladies) + +# Cas 2: importation d'un fichier excel en format long +DataMaladies <- read.xlsx("Maladies_Régions.xlsx", "long", colNames = TRUE) +head(DataMaladies) +str(DataMaladies) +summary(DataMaladies) +class(DataMaladies) +# mais régions et maladies sont en caractère +DataMaladies <- mutate_if(DataMaladies, is.character, as.factor) +summary(DataMaladies) +chisq.test(DataMaladies$Région, DataMaladies$Maladie) + +# Cas 3 : importation d'un fichier excel en format large +DataMaladies <- read.xlsx("Maladies_Régions.xlsx", + colNames = TRUE, + rowNames = TRUE) +(DataMaladies) +str(DataMaladies) +chisq.test(DataMaladies) +# En fait il faut déclarer rowNames = TRUE + +``` + +### complément du khi² : l'analyse factorielle des correspondances + +```{r, complement AFC} +require(Factoshiny) +require(FactoMineR) +load("DataTitanic") + +table(DataTitanic$Classe, DataTitanic$Survie) +chisq.test(DataTitanic$Classe, DataTitanic$Survie) +DataTitanic $ Survie = + as.factor (DataTitanic $ Survie) +DataTitanic <- mutate_if(DataTitanic, is.character, as.factor) +summary(DataTitanic) +survie_age <- table(DataTitanic$Survie, DataTitanic$Age) +chisq.test(survie_age) +survie_sexe <- table(DataTitanic$Survie, DataTitanic$Sexe) +chisq.test(survie_sexe) +survie_embarq <- table(DataTitanic$Survie, DataTitanic$Embarq) +chisq.test(survie_embarq) +# realisation de l'AFC +(survie_age) +class(survie_age) +mode(survie_age) +(survie_age_df <- as.data.frame(survie_age)) +class(survie_age_df) +class(children) # nuance : la première colonne est rownames +# il faut donc convertir en rownames la colonne Var1 de survie_age + + +survie_age_afc <- as.data.frame(survie_age) +survie_age_afc <- pivot_wider(survie_age_afc, names_from = Var2, values_from = Freq) +(survie_age_afc) +rownames(survie_age_afc) <- survie_age_afc[,1] # ça ne marche plus ! +# mais comme cela ça marche : +survie_age_afc <- survie_age_afc %>% + remove_rownames %>% + column_to_rownames(var="Var1") +# on ne peut plus le forcer = plus de risque de le faire accidentellement ! +afc_titanic_age <- CA(survie_age_afc) +summary(afc_titanic_age) + +# Lancement du modèle +ModeleRegLog1 = glm (data = DataTitanic, family = "binomial", Survie ~. , ) +library(car) +Anova (ModeleRegLog1) # library car +# Accès aux infos du modèle +ModeleRegLog1 $ null.deviance +ModeleRegLog1 $ deviance +ModeleRegLog1 $ coefficients +# Accès aux coefficients par la fonction tbl_regression du package gtsummary +library ( gtsummary ) +tbl_regression ( ModeleRegLog1 ) +tbl_regression ( ModeleRegLog1, exponentiate = TRUE) + +# avec interactions : +ModeleRegLog2 = glm (data = DataTitanic, family = "binomial", Survie ~ Sexe * Classe , ) +library(car) +Anova (ModeleRegLog2) # library car +# Accès aux infos du modèle +ModeleRegLog2 $ null.deviance +ModeleRegLog2 $ deviance +ModeleRegLog2 $ coefficients +# Accès aux coefficients par la fonction tbl_regression du package gtsummary +library ( gtsummary ) +tbl_regression ( ModeleRegLog2 ) +tbl_regression ( ModeleRegLog2, exponentiate = TRUE) + + + +``` + +Pour Quarto voir : . + +## Tests avec fonctions ie() + +```{r, fonction ie avec choix fichier oar filechoose} + +ie() # fonction ouvrant une fenêtre explorateur pour choisir le fichier +# sélectionnez le fichier Data xl Data Sante.xlsx + +DS <- ie() +summary(DS) +# testons de comparaison à une valeur de l'âge moyen à 40 ans : +t.test(x = DS$AGE, mu = 40) +``` + +```{r, Mann-Whitney} + +# comparer deux médianes +fg <- coller() +# on ne peut pas faire de test t classique ! On a pas de choix ! +glimpse(fg) +summary(fg) +t.test(fg$F, fg$G) +plot(fg$F,fg$G) +shapiro.test(fg$F) +shapiro.test(fg$G) + +# Test de Mann Whitney +wilcox.test(fg$F,fg$G) +plot(log(fg$F), log(fg$G)) +``` + +### paquetage nortest + +[nortest](https://www.normalesup.org/~carpenti/Notes/Normalite/Dago-test.html) + +```{r} +pt(2, 48, lower.tail = TRUE, log.p = FALSE) +``` + +\[distribution t dans R\]() + +==\> trouver la formule probabilité qu'un classement à n individus soit classés séparément sur deux variables == \> pour tests non paramétriques ! + +### calculs de puissances avec pwrss + +[paquetage pwrss](https://cran.r-project.org/web/packages/pwrss/vignettes/examples.html) + +```{r, puissance} +library(pwrss) +model <- lm(mpg ~ hp + wt, data = mtcars) +summary(model) +power.t.test(ncp = -3.519, # t-value for hp variable + df = 29, # residual degrees of freedom + alpha = 0.05, # type 1 error rate + alternative = "two.sided", + plot = TRUE) + +apropos("power") +stats::power.t.test(n = 15, delta = 10, sd = 15.0, sig.level = 0.05) + +# revenons à notre test initial : +t.test(Data2M$INOX, Data2M$ALU) +power.t.test(ncp = -3.0451, # t-value for hp variable + df = 20, # residual degrees of freedom + alpha = 0.05, # type 1 error rate + alternative = "two.sided", + plot = TRUE) + +# on peut rajouter les autres cas envisagés : +t.test(Data2M$INOX, Data2M$ALU, var.equal = TRUE) +power.t.test(ncp = -3.0451, # t-value for hp variable + df = 26, # residual degrees of freedom + alpha = 0.05, # type 1 error rate + alternative = "two.sided", + plot = TRUE) +# test T en données appariées : moyennes des différences +t.test(Data2M$INOX, Data2M$ALU, var.equal = TRUE, paired = TRUE) +power.t.test(ncp = -3.5129, # t-value for variable + df = 13, # residual degrees of freedom + alpha = 0.05, # type 1 error rate + alternative = "two.sided", + plot = TRUE) +## notez que le paramètre type = est refusé par la fonction... + +``` + +**Attention avec power.t.test() de stats !** Il est masqué par pwrss ! + +## Utilisation de GPower + +**Tres très utile pour vérifier la théorie et évaluer les puissances très vite** + +## Test de Fischer sur régression + +```{r, test de Fischer sur régression linéaire} +temperature <- ie() +summary(temperature) +# on explique la température par le temps ! +mod_1 <- lm(Temp.Moyenne ~ Année, data = temperature) +summary(mod_1) +power.f.test(ncp = 1, df1 = 1, df2 = 74, alpha = 0.05) +power.f.test(ncp = 63, df1 = 1, df2 = 74, alpha = 0.05) +## essayons de voir sur l'anomalie de température : +norm_temp <- mean(temperature$Temp.Moyenne[46:76]) +temperature <- mutate(temperature, anomalie = Temp.Moyenne - norm_temp) +summary(temperature) +smooth <- loess(temperature$anomalie ~ temperature$Année) +plot(temperature$Année, temperature$anomalie) +lines(predict(smooth), col = 'red', lwd = 2) +require(tidyverse) +ggplot(temperature, + aes(temperature$Année, temperature$anomalie)) + + geom_point() + + geom_smooth() +``` + +## tests sur proportions + +comparaison d'une proportion à une valeur donnée : + +```{r, test sur proportion} +binom.test(n = 150, x = 100, p = 0.50) +binom.test(n = 150, x = 85, p = 0.50) +binom.test(n = 150, x = 95, p = 0.50) ### sondage présidentielles binom.test(n = 30000, x = 14700, p = 0.50) +power.binom.test(size = 150, 0.5, alpha = 0.05, null.prob = 0.5, alternative = "two.sided") +``` + +### comparaison de deux proportions : + +```{r, comparaison de deux proportions} +prop.test(c(60,24), c(200,160)) +power.z.twoprops(prob1 = 0.30, prob2 = 0.15, + power = 0.90, arcsine = TRUE) +probs.to.h(prob1 = 0.30, prob2 = 0.15) +``` + + diff --git a/corrplot_ou_ggplot_representer_correlations.R b/corrplot_ou_ggplot_representer_correlations.R deleted file mode 100644 index 246b08e..0000000 --- a/corrplot_ou_ggplot_representer_correlations.R +++ /dev/null @@ -1,76 +0,0 @@ -### représenter une matrice de corrélations dans ggplot en mosaiques -# https://stackoverflow.com/questions/39136211/title-in-r-corrplot-too-not-centred-and-too-high - - -# problèmes de titres avec corrplot: -# https://stackoverflow.com/questions/40509217/how-to-have-r-corrplot-title-position-correct -# https://github.com/taiyun/corrplot/issues/10 -# changer noms de variables dans corrplot: -# https://github.com/taiyun/corrplot/issues/20 - -# très éclairant: -# https://stackoverflow.com/questions/41679136/r-corrplot-crops-bottom-axis-label - -#### solution corrplot ----- -"VADeaths" <- - structure(c(11.7, 18.1, 26.9, 41, 66, 8.7, 11.7, 20.3, 30.9, 54.3, 15.4, - 24.3, 37, 54.6, 71.1, 8.4, 13.6, 19.3, 35.1, 50), .Dim = c(5, 4), - .Dimnames = list(c("50-54", "55-59", "60-64", "65-69", "70-74"), - c("Rural Male", "Rural Female", "Urban Male", "Urban Female"))) - -library(corrplot) -cors = cor(VADeaths) -corrplot(cors,tl.col="black",title="Example Plot",mar=c(0,0,5,0),tl.offset = 1) -### mexte et options mar attention aux options tl. elles s'appliquent aux différents éléments de texte -corrplot(cors,tl.col="black", mar=c(0,0,5,0), tl.offset = 1) -mtext("Example Plot", at=2.5, line=-0.5, cex=2) - - -#### reshape et mosaique ggplot ---- - -library(reshape2) -cors <- cor(VADeaths) -cor_data <- reshape2::melt( - cors, - varnames = paste0("demographic", 1:2), - value.name = "correlation" -) - -Then draw the plot. - -library(ggplot2) -ggplot(cor_data, aes(demographic1, demographic2, fill = correlation)) + - geom_tile() + - ggtitle("Correlation across demographics for VA deaths") - -# emploi de tl.offset: -# https://stackoverflow.com/questions/5359619/r-change-size-of-axis-labels-for-corrplot - -# un autre stacks: -# https://stackoverflow.com/questions/39029526/how-to-change-the-margins-of-a-correlation-matrix-plot - -library(corrplot) -cor_matrix <- structure(c(1, 0.31596392056465, -0.120092224085334, -0.345097115278159, - 0.31596392056465, 1, 0.158912865564527, -0.606426850726639, -0.120092224085334, - 0.158912865564527, 1, -0.134795548155303, -0.345097115278159, - -0.606426850726639, -0.134795548155303, 1), .Dim = c(4L, 4L), - .Dimnames = list(NULL, c("var_1", "var_2", "var_3", "var_4"))) - -corrplot.mixed(cor_matrix, order = "AOE", upper = "ellipse", lower = "number", - tl.cex = 2, cl.cex = 2, number.cex = 2) - -### réponse possible demandant autre package: -library(corrplot) -library(scico) - -col4 <- scico(100, palette = 'vik') # définition d'une palette par scico -filetag <- "corrplot_result.png" - -png(filetag, height = 800, width = 800) # création d'un fichier png ! - -corrplot.mixed(cor_matrix, order = "AOE", upper = "ellipse", lower = "number", - upper.col = col4, lower.col = col4, - tl.cex = 2, cl.cex = 2, number.cex = 2) -dev.off() -# https://www.r-graph-gallery.com/74-margin-and-oma-cheatsheet.html -# https://bookdown.org/ndphillips/YaRrr/arranging-plots-with-parmfrow-and-layout.html diff --git "a/data/2 mat\303\251riaux.xlsx" "b/data/2 mat\303\251riaux.xlsx" new file mode 100644 index 0000000..d2452c9 Binary files /dev/null and "b/data/2 mat\303\251riaux.xlsx" differ diff --git a/data/DM b/data/DM new file mode 100644 index 0000000..a7b71ef Binary files /dev/null and b/data/DM differ diff --git a/data/DM.rds b/data/DM.rds new file mode 100644 index 0000000..33e97d4 Binary files /dev/null and b/data/DM.rds differ diff --git a/data/Data Sante.xlsx b/data/Data Sante.xlsx new file mode 100644 index 0000000..ad06023 Binary files /dev/null and b/data/Data Sante.xlsx differ diff --git a/data/Data2M.rds b/data/Data2M.rds new file mode 100644 index 0000000..17164f5 Binary files /dev/null and b/data/Data2M.rds differ diff --git a/data/DataTitanic b/data/DataTitanic new file mode 100644 index 0000000..4818f17 Binary files /dev/null and b/data/DataTitanic differ diff --git a/data/TCMaladie b/data/TCMaladie new file mode 100644 index 0000000..f73c855 Binary files /dev/null and b/data/TCMaladie differ diff --git a/data/__donnees b/data/__donnees new file mode 100644 index 0000000..2db35e1 --- /dev/null +++ b/data/__donnees @@ -0,0 +1 @@ +fichiers de données diff --git a/exemple_powerpoint.Rmd b/exemple_powerpoint.Rmd deleted file mode 100644 index 6629446..0000000 --- a/exemple_powerpoint.Rmd +++ /dev/null @@ -1,34 +0,0 @@ ---- -title: "Exemple creation powerpoint" -author: "Franck Nadaud" -date: "2024-01-25" -output: pdf_document ---- - -```{r setup, include=FALSE} -knitr::opts_chunk$set(echo = TRUE) -``` - -## R Markdown - -This is an R Markdown document. Markdown is a simple formatting syntax for authoring HTML, PDF, and MS Word documents. For more details on using R Markdown see . - -When you click the **Knit** button a document will be generated that includes both content as well as the output of any embedded R code chunks within the document. You can embed an R code chunk like this: - ---- - -```{r cars} -summary(cars) -``` - -## Including Plots - -You can also embed plots, for example: - ---- - -```{r pressure, echo=FALSE} -plot(pressure) -``` - -Note that the `echo = FALSE` parameter was added to the code chunk to prevent printing of the R code that generated the plot. diff --git a/exemple_powerpoint_2.Rmd b/exemple_powerpoint_2.Rmd deleted file mode 100644 index 6afde84..0000000 --- a/exemple_powerpoint_2.Rmd +++ /dev/null @@ -1,44 +0,0 @@ ---- -title: "Exemple creation powerpoint" -author: "Franck Nadaud" -date: "2024-01-25" -output: - powerpoint_presentation: - reference_doc: PPT_cired_bleu_vide.pptx ---- - -```{r setup, include=FALSE} -knitr::opts_chunk$set(echo = TRUE) -``` - -## R Markdown - -This is an R Markdown document. Markdown is a simple formatting syntax for authoring HTML, PDF, and MS Word documents. For more details on using R Markdown see . - -When you click the **Knit** button a document will be generated that includes both content as well as the output of any embedded R code chunks within the document. You can embed an R code chunk like this: - ------------------------------------------------------------------------- - -```{r cars} -summary(cars) -``` - -## Including Plots - -You can also embed plots, for example: - ------------------------------------------------------------------------- - -```{r pressure, echo=FALSE} -plot(pressure) -``` - -Note that the `echo = FALSE` parameter was added to the code chunk to prevent printing of the R code that generated the plot. - ------------------------------------------------------------------------- - -On peut même écrire des équations. - -$$ -w_i = a + bx_i+cy_i + \epsilon_i -$$ diff --git a/exemple_word.Rmd b/exemple_word.Rmd deleted file mode 100644 index 0bd9dc8..0000000 --- a/exemple_word.Rmd +++ /dev/null @@ -1,30 +0,0 @@ ---- -title: "Exemple" -author: "Franck Nadaud" -date: "2024-01-25" -output: word_document ---- - -```{r setup, include=FALSE} -knitr::opts_chunk$set(echo = TRUE) -``` - -## R Markdown - -This is an R Markdown document. Markdown is a simple formatting syntax for authoring HTML, PDF, and MS Word documents. For more details on using R Markdown see . - -When you click the **Knit** button a document will be generated that includes both content as well as the output of any embedded R code chunks within the document. You can embed an R code chunk like this: - -```{r cars} -summary(cars) -``` - -## Including Plots - -You can also embed plots, for example: - -```{r pressure, echo=FALSE} -plot(pressure) -``` - -Note that the `echo = FALSE` parameter was added to the code chunk to prevent printing of the R code that generated the plot. diff --git a/ggplot.R b/ggplot.R deleted file mode 100644 index ddd2469..0000000 --- a/ggplot.R +++ /dev/null @@ -1,392 +0,0 @@ -############################################################################### -###### graphismes en ggplot ############ -############################################################################### - -### chargement des paquetages ---- -library(magrittr) # paquetage n?cessaire pour utiliser le tuyau ou pipe de programmation -library(gapminder) -library(tidyverse) -library(SmartEDA) -(.packages()) -### d?finition du r?pertoire de travail ---- -setwd("D:/cours_R") -#setwd("c:/Users/user/desktop/Cours_R") ### changez cela dans votre environnement -getwd() # afficher le r?pertoire de travail. -theme_set(theme_bw()) # pre-set the bw theme. - -### pr?lude ? ggpplot: fonctions graphiques de smarteda ---------- -# https://towardsdatascience.com/eda-in-r-with-smarteda-eae12f2c6094 -# les fonctions de SmartEDA encapsulent des commandes ggplot2 pr?d?finies - -#### graphiques basiques : Variables quantitatives --- - -## Par d?faut, ExpNumViz calcule des distributions par noyaux des variables quantitatives -densites_gapmind <- ExpNumViz(gapmind.2007.19, - target = NULL, - nlim = 10, - Page = c(3,3)) -densites_gapmind[[1]] # notez la subtilit? de l'indexation double crochet: -class(densites_gapmind) -double <- densites_gapmind[[1]] -class(double) -mode(double) - -simple <- densites_gapmind[1] -class(simple) -mode(simple) - -# https://cran.r-project.org/doc/manuals/R-lang.html#Indexing -mode(densites_gapmind) # c'est une liste d'objets -class(densites_gapmind) # de classe liste -str(densites_gapmind) -# c'est donc une liste compos?e de 1 objet contenant 3 gtable - - -### variables qualitatives: -ciredium <- rgb(67, 135, 135, max = 255) -class(ciredium) -library(RColorBrewer) -(.packages()) -display.brewer.all() - -barres_gapmind <- ExpCatViz(gapmind.2007.19, - target = NULL, - col = ciredium, - clim = 10, - margin = 2, - Page = c(2,1)) -barres_gapmind[[1]] -barres_gapmind -class(barres_gapmind) -mode(barres_gapmind) -str(barres_gapmind) - -### En fait, lorsque target = NULL, les autres param?tres sont ignor?s, -# il g?n?re les courbes de densit? de toutes les variables selon page etc. - -# https://www.datamentor.io/r-programming/color/ -rgb(67,135,135, max = 255) -ciredium <- "#438787" - -barres_HDI_Class <- ExpCatViz(gapmind.2007.19, - target = "HDI_Class", - col = NULL, - clim = 10, - margin = 2, - Page = c(2,1)) -barres_HDI_Class[[1]] - - - -# choisissons une variables quantitative : -graph_GDI_2019 <- ExpNumViz(gapmind_2007_19[,-2], target = "GDI_2019", nlim = 10, Page = c(2,2)) -graph_GDI_2019[[1]] # on obtient une liste de nuages de points entre le GDI_2019. - -# si on execute la commande sans l'affecter ? un objet on obtient ceci: -ExpNumViz(gapmind_2007_19[,-2], target = "GDI_2019", nlim = 10, Page = c(2,2)) #notez qu'il ignore l'indice -2 ! - -### on peut aussi des pr?ciser des variables cibles, toujours en indexant: -ExpNumViz(gapmind_2007_19, target = "GDI_2019", nlim = 10)[4:6] -ExpNumViz(gapmind_2007_19, target = "GDI_2019", nlim = 10, - gtitle = "Indicateur de d?veloppement genr?", theme = "Default") -titre_GDI_2019 <- ExpNumViz(gapmind_2007_19, target = "GDI_2019", nlim = 10, - gtitle = "Indicateur de d?veloppement genr?", theme = "Default", Page = c(2,2)) -titre_GDI_2019[[1]] -ExpNumViz(gapmind_2007_19, scatter = TRUE) # noter l'index relatif - -### cible == variable qualitative -ExpNumViz(gapmind_2007_19, target = "GDI_Group_2019", nlim = 10, - gtitle = "Indicateur de d?veloppement genr?", theme = "Default") -box_hdi_class <- ExpNumViz(gapmind_2007_19, target = "HDI_Class", nlim = 10, - gtitle = "Variables quantitatives par groupe HDI", theme = "Default") -box_hdi_class[[4]] -rm(box_hdi_class) -ExpNumViz(gapmind_2007_19, target = "HDI_Class", nlim = 10, - gtitle = "Variables quantitatives par groupe HDI", theme = "Default") - -# http://adv-r.had.co.nz/Subsetting.html -# https://bookdown.org/rdpeng/rprogdatascience/subsetting-r-objects.html - -### graphiques quantiles-quantiles ---- -gapmindQQ <- ExpOutQQ(gapmind.2007.19, - nlim = 10, - Page = c(2,2)) -gapmindQQ -ExpOutQQ(gapmind.2007.19, nlim = 10) - -### coordonn?es parall?les ----- -ExpParcoord(gapmind.2007.19, Nvar = c("GDI_2019", "gdpPercap", "lifeExp", "Gender_Inequality_2019")) -ExpParcoord(gapmind.2007.19, - Group = "continent", - Nvar = c("GDI_2019", "gdpPercap", "lifeExp", "Gender_Inequality_2019")) -ExpParcoord(gapmind.2007.19, - Group = "Stadev", - Nvar = c("GDI_2019", "Gender_Inequality_2019", "gdpPercap", "lifeExp")) -ExpParcoord(gapmind.2007.19, - Group = "HDI_Class", - Nvar = c("GDI_2019", "Gender_Inequality_2019", "gdpPercap", "lifeExp", "urban_pop_2019")) - - -### ajouter passage sur corrplot. -# https://cran.r-project.org/web/packages/corrplot/vignettes/corrplot-intro.html -# http://www.sthda.com/french/wiki/visualiser-une-matrice-de-correlation-par-un-correlogramme - -### visualisons les corr?lations avec le paquetage corrplot -# on doit va utiliser la m?thode corrplot... -library(corrplot) -# Elle n'admet que des donn?es num?riques en entr?e et g?re les NA -# pour cela il faut calculer une matrice de corr?lation ds donn?es avec cor() -gapcor <- cor(gapmind.2007.19[,c(4:6,8:16)], use = "complete.obs") # on a vir? les NAs -round(gapcor,2) # on demande d'afficher la matrice avec deux d?cimales -class(gapcor) -View(gapcor) -# il pourrait ?tre int?ressant d'utiliser les corr?lations de rangs (sur des classements) -gapcor.kendall <- cor(gapmind.2007.19[,c(4:6,8:16)], use = "complete.obs", method = "kendall") -round(gapcor.kendall,2) ### notez la diff?rence entre les deux matrices ! -gapcor.spearman <- cor(gapmind.2007.19[,c(4:6,8:16)], use = "complete.obs", method = "spearman") -round(gapcor.spearman,2) ### notez la diff?rence entre les deux matrices ! - -### corrplot admet une matrice de correlation entr?e -corrplot(gapcor, method = "circle") # corrplot admet en entr?e une matrice corr?lation -corrplot(gapcor.kendall, method = "circle") # noter les diff?rences avec la premi?re matrice -corrplot(gapcor.spearman, method = "circle") # noter les diff?rences avec la premi?re matrice - -### on peut changer de m?thodes de visualisation: -corrplot(gapcor, method = "pie") # des secteurs... noter les corr?lations tr?s faibles de pop -corrplot(gapcor, method = "color") # des cases color?es -corrplot(gapcor, method = "number") # le coefficient -corrplot(gapcor, method = "ellipse") # cercle allong? dans la direction de corr?lation -corrplot(gapcor, method = "shade") # la case color?e avec une hachure pour les n?gatives -### ou encore l'implantation -corrplot(gapcor, method = "ellipse", type = "upper") # aussi "lower", defaut = "full" -# changer l'aspect et les couleurs: -col.cor <- colorRampPalette(c("red", "white", "blue"))(20) -corrplot(gapcor, method = "color", col = col.cor) # une ?chelle ? 21 ?chelons -corrplot(gapcor, method = "circle", col = c("black", "white"), bg = "#438787") # noir blanc, fond ciredium ! - -### l'int?r?t de corrplot est qu'il propose une selection d'options int?ressantes -# l'analyse exploratoire: la plus int?ressante est de r?ordonner les variables de la matrice: -corrplot(gapcor, method = "ellipse", order = "hclust") -corrplot(gapcor, method = "circle", col = col.cor, order = "hclust") - -### utilisons des palettes pr?d?finies -library(RColorBrewer) # tr?s pratique, on l'utilisera intensivement dans la partie ggplot ! -corrplot(gapcor, method = "ellipse", order = "hclust", col = brewer.pal(n = 8, name = "RdBu"), bg = "#438787") -corrplot(gapcor, method = "ellipse", order = "hclust", - col = brewer.pal(n = 8, name = "PuOr"), bg = "#438787", tl.col="black") -### on peut personnaliser fortement l'affichage: -corrplot(gapcor, method = "color", col = NULL, - type = "upper", order = "hclust", - addCoef.col = "black", # Ajout du coefficient de corr?lation - tl.col = "black", tl.srt = 45, #Rotation des etiquettes de textes - # Cacher les coefficients de corr?lation sur la diagonale - diag=FALSE -) # r?sultat int?ressant mais pas tr?s beau -corrplot(gapcor, method = "ellipse", order = "hclust", tl.srt = 45, - col = brewer.pal(n = 11, name = "PuOr"), bg = "#438787", tl.col="black", - title = "Corr?lations des donn?es ONU") -# on peut par contre faire varier l'ordre du trac? des corr?lations. -# m?thode d'?cart angulaire aux valeurs propres: -corrplot(gapcor, method = "ellipse", order = "AOE", tl.srt = 45, - col = brewer.pal(n = 11, name = "PuOr"), bg = "#438787", tl.col="black", - title = "Corr?lations des donn?es quantitatives ONU") # remarquez l'agencement diff?rent des corr?lations ! -# classement par coordonn?es sur la premi?re composante principale: -corrplot(gapcor, method = "ellipse", order = "FPC", tl.srt = 45, - col = brewer.pal(n = 11, name = "PuOr"), bg = "#438787", tl.col="black", - title = "Corr?lations des donn?es quantitatives ONU") # remarquez l'agencement diff?rent des corr?lations ! - -### on peut aussi varier la m?thode de classification dans hclust: -corrplot(gapcor, method = "ellipse", order = "hclust", hclust.method = "complete", - tl.srt = 45, col = brewer.pal(n = 11, name = "PuOr"), - bg = "#438787", tl.col="black", - title = "Corr?lations des donn?es ONU, r?ordonn?es par CAHI en lien complet") - -# lien simple -corrplot(gapcor, method = "ellipse", order = "hclust", hclust.method = "single", - col = brewer.pal(n = 11, name = "PuOr"), bg = "#438787", - tl.col = "black", tl.cex = 0.8, tl.srt = 45, - title = "Corr?lations des donn?es ONU, r?ordonn?es par CAHI en lien simple") - -# lien moyen -corrplot(gapcor, method = "ellipse", order = "hclust", hclust.method = "average", - tl.srt = 45, col = brewer.pal(n = 11, name = "PuOr"), - bg = "#438787", tl.col = "black", tl.cex = 0.8, - title = "Corr?lations des donn?es ONU, r?ordonn?es par CAHI en lien moyen", - line = -2) - -# lien centroid -corrplot(gapcor, method = "ellipse", order = "hclust", hclust.method = "centroid", - tl.srt = 45, col = brewer.pal(n = 11, name = "PuOr"), - bg = "#438787", tl.col="black", tl.cex = 0.8, - title = "Corr?lations des donn?es ONU, r?ordonn?es par CAHI centro?de", - line = -2) - -# lien m?dian -corrplot(gapcor, method = "ellipse", order = "hclust", hclust.method = "median", - tl.srt = 45, col = brewer.pal(n = 11, name = "PuOr"), - bg = "#438787", tl.col="black", tl.cex = 0.8, - title = "Corr?lations des donn?es ONU, r?ordonn?es par CAHI m?dian", - line = -2) - -# ward -corrplot(gapcor, method = "ellipse", order = "hclust", hclust.method = "ward", - tl.srt = 45, col = brewer.pal(n = 11, name = "PuOr"), - bg = "#438787", tl.col="black", tl.cex = 0.8, - title = "Corr?lations des donn?es ONU, r?ordonn?es par CAHI en distance de ward", line = -2) -# ward.d -corrplot(gapcor, method = "ellipse", order = "hclust", hclust.method = "ward.D", - tl.srt = 45, col = brewer.pal(n = 11, name = "PuOr"), - bg = "#438787", tl.col="black", tl.cex = 0.9, - title = "Corr?lations des donn?es ONU, r?ordonn?es par CAHI en distance de ward.D", line = -2) - -# ward.d2 -corrplot(gapcor, method = "ellipse", order = "hclust", hclust.method = "ward.D2", - tl.srt = 45, col = brewer.pal(n = 11, name = "PuOr"), - bg = "#438787", tl.col="black", tl.cex = 0.9, - title = "Corr?lations des donn?es ONU, r?ordonn?es par CAHI en distance de ward.D2", line = -2) - -#mcquitty -corrplot(gapcor, method = "ellipse", order = "hclust", hclust.method = "mcquitty", - tl.srt = 45, col = brewer.pal(n = 11, name = "PuOr"), - bg = "#438787", tl.col="black", tl.cex = 0.9, - title = "Corr?lations des donn?es ONU, r?ordonn?es par CAHI en distance de MacQuitty", line = -2) - -#mcquitty rect.col = 2 ou 6 ou 5 -corrplot(gapcor, method = "ellipse", order = "hclust", hclust.method = "mcquitty", addrect = 3, - tl.srt = 45, col = brewer.pal(n = 11, name = "PuOr"), rect.col = 2, rect.lwd = 2, - bg = "#438787", tl.col="black", tl.cex = 0.9, - title = "Corr?lations des donn?es ONU, r?ordonn?es par CAHI en distance de MacQuitty", line = -2) -### il existe une version mixte: -corrplot.mixed(gapcor) # plus limit?e et autres options - - -### ajouter: exercices == faire de m?me sur les matrices de corr?lations de rangs et comparer ! -### d?cision ! - - - -### Commencer en GGplot ---- -# installer ggthemes: -install.packages("ggthemes") - -(.packages()) -### les fondamentaux de ggplot sur les donn?es gapmind_2007_19 -# https://www.datanovia.com/en/fr/lessons/introduction-a-ggplot2/ -# -# appliquer les esth?tiques aux variables: -# boxplot: en x OU y - -ggplot(gapmind.2007.19, - aes(y = GDP_GUSDPPP_2017)) + - geom_boxplot() - - -ggplot(gapmind.2007.19, - aes(y = GDI_2019)) + - geom_boxplot() - -ggplot(gapmind.2007.19, - aes(x = GDP_GUSDPPP_2017)) + - geom_boxplot() - -ggplot(gapmind.2007.19, aes(x = GDI_2019)) + - geom_boxplot() - -### on peut afficher les points sur un boxplot en cr?ant un facteur fictif: -ggplot(gapmind.2007.19, - aes(x = factor(1), - y = GDI_2019)) + - geom_boxplot(width = 0.5) + - geom_jitter(width = 0.1) # jitter = d?placer les points l?g?rement de 10 % - -### nuage de points: -ggplot(gapmind.2007.19, - aes(x = GDP_GUSDPPP_2017, - y = GDI_2019)) + - geom_point() -## on peut utiliser des fonctions sur des variables dans l'esth?tique: -ggplot(gapmind.2007.19, - aes(x = log(GDP_GUSDPPP_2017), - y = GDI_2019)) + - geom_point() - -ggplot(gapmind.2007.19, - aes(x = log(GDP_GUSDPPP_2017), - y = Gender_Inequality_2019)) + - geom_point() - -ggplot(gapmind.2007.19, - aes(x = log(GNI_2019), - y = Gender_Inequality_2019)) + - geom_point() + - geom_smooth() - -### noter la diff?rence de position de l'esth?tique dans les commandes: -# Utilisez ceci -attach(gapmind.2007.19) # attacher le tibble nomm? aux commandes -detach(gapmind.2007.19) # d?tacher le tibble nomm? aux commandes -ggplot(gapmind.2007.19, - aes(log(gdpPercap), urban_pop_2019)) + - geom_point() + - geom_smooth() - -# ou ceci -ggplot(gapmind.2007.19) + - geom_point(aes(log(gdpPercap), urban_pop_2019)) - -## diff?rence entre couleur et remplissage: -# Couleur -ggplot(gapmind.2007.19, aes(GDI_2019, HDI_Class)) + - geom_boxplot(aes(color = HDI_Class)) -class(gapmind.2007.19$HDI_Class) - -# Remplir -ggplot(gapmind.2007.19, aes(HDI_Class, GDI_2019)) + - geom_boxplot(aes(fill = HDI_Class)) -# on a juste un petit probl?me de chevauchement des ?tiquettes d'axes. -ggplot(gapmind.2007.19, aes(HDI_Class, GDI_2019)) + - geom_boxplot(aes(fill = HDI_Class)) + - theme(axis.text.x = element_text(angle = 90, vjust = 0.5, hjust = 1)) -# notez comment il vous avertis de l'?viction des NA. -# On pourrait gagner un peu de place dans l'espace de tra?age en changeant l'angle: - -# on peut affecter un objet: -boxplot_hdi_class <- ggplot(gapmind.2007.19, - aes(HDI_Class, GDI_2019)) + - geom_boxplot(aes(fill = HDI_Class)) + - labs(title = "Indicateur d'inégalité de genre selon l'HDI", - subtitle = "HDI = indicateur synthétique de développement humain ONU", - caption = "Source: ONU", - x = "Niveau HDI", - y = "Indicateur d'inégalités genré (2019)") + - theme(axis.text.x = element_text(angle = 45, vjust = 0.5, hjust = 0.5)) -(boxplot_hdi_class) -##sauvegarder l'objet ggplot: -ggsave("boxplot_hdi_class.png", device = "png") -#rm(xplot_hdi_class) - -# il faut afficher l'objet: -boxplot_hdi_class # l'objet peut ?tre modifi?, puis enregistr? etc... -str(boxplot_hdi_class) # noter la liste de param?tres ajustables ! -class(boxplot_hdi_class) -mode(boxplot_hdi_class) - - -### changer theme -#https://ggplot2.tidyverse.org/reference/ -theme_set(theme_grey()) - -boxplot_hdi_class_wrap <- ggplot(gapmind.2007.19, - aes(HDI_Class, GDI_2019)) + - geom_boxplot(aes(fill = HDI_Class)) + - facet_wrap(vars(continent)) + - labs(title = "Indicateur d'inégalité de genre selon l'HDI", - subtitle = "HDI = indicateur synthétique de développement humain ONU", - caption = "Source: ONU", - x = "Niveau HDI", - y = "Indicateur d'inégalités genré (2019)") + - theme(axis.text.x = element_text(angle = 45, vjust = 0.5, hjust = 0.5)) -(boxplot_hdi_class_wrap) - - - diff --git a/references/.rprofile b/references/.rprofile new file mode 100644 index 0000000..96f2b14 --- /dev/null +++ b/references/.rprofile @@ -0,0 +1,69 @@ +print ("Bonjour") + +# library (FactoMineR) +# library (car) +# library (doBy) +library (openxlsx) +library(rstatix) +# library (Factoshiny) + +####################################################### +# la fonction coller permet de faire une importation par +coller = function () +{ + read.table("clipboard", header=TRUE, sep="\t", dec = ",") +} +####################################################### +# permet d'importer de l'Excel +ie = function () +{ + read.xlsx( file.choose() ) +} + +####################################################### +# Extraction des colonnes numériques d'un dataframe +DfNum = function(DataFrameEntree) +{ + DataFrameSortie = DataFrameEntree [ sapply ( X = DataFrameEntree, is.numeric ) == TRUE] + return(DataFrameSortie) +} + +############################################################################################ +# Fonction qui effectue le test du Khi Deux des combinaisons des variables d'un dataframe +FKhiDeux = function (DataFrameEntree) +{ + # Récupère le nom du DataFrame passé en entrée + NomDataFrame = deparse(substitute(DataFrameEntree)) + + # Récupère les noms des colonnes du dataframe + DataFrameEntree = DfTexte(DataFrameEntree) + NomVariables = names (DataFrameEntree) + + # Crée un dataframe avec 2 colonnes contenant toutes ls combinaisons croisées des Noms des variables + DataFrameSortie = as.data.frame(t(combn(x=NomVariables, m = 2))) + + i = 1 + while (i<=nrow(DataFrameSortie)) + { + # Récupération de la p-value + PValueLocale = + chisq.test( + DataFrameEntree [,DataFrameSortie [i,1]], + DataFrameEntree [,DataFrameSortie [i,2]] + )$p.value + + # Stockage de la p-value du test du Khi ² + DataFrameSortie$PValueKhiDeux [i] = PValueLocale + i = i + 1 + } + + # Ajout de la colonne SIGnificatif ou pas (avec un alpha de 0.05) + + DataFrameSortie$Sig = ifelse(DataFrameSortie$PValueKhiDeux<0.05, "SIG", "NON SIG") + + # Retour du dataframe de synthèse + return (DataFrameSortie) +} +##################################################################################### + +print ("A Bientôt!!") diff --git a/references/references b/references/references new file mode 100644 index 0000000..abd5e95 --- /dev/null +++ b/references/references @@ -0,0 +1 @@ +this directory of references