├── .travis.yml ├── DESCRIPTION ├── LICENSE ├── NAMESPACE ├── R ├── Functions.R ├── dada2.R ├── data.R ├── glmr.R ├── misc.R ├── plot.R └── zzz.R ├── README.md ├── data └── Physeq.rda ├── man ├── betadiv.Rd ├── betatest.Rd ├── biomarker.Rd ├── buildTree.Rd ├── data-Physeq.Rd ├── data-physeq.Rd ├── difftest.Rd ├── distcolor.Rd ├── do_aov.Rd ├── do_ttest.Rd ├── do_wilcox.Rd ├── dot-checkfile.Rd ├── dot-getstar.Rd ├── dot-lda.fun.Rd ├── glmr.Rd ├── ldamarker.Rd ├── lightcolor.Rd ├── normalize.Rd ├── otu_table.Rd ├── phy_tree.Rd ├── plotLDA.Rd ├── plotalpha.Rd ├── plotbar.Rd ├── plotbeta.Rd ├── plotdiff.Rd ├── plotmarker.Rd ├── plotquality.Rd ├── preRef.Rd ├── prefilter.Rd ├── processSeq.Rd ├── psmelt.Rd ├── richness.Rd ├── sample_data.Rd ├── subset_samples.Rd ├── subset_taxa.Rd └── tax_table.Rd ├── microbial.Rproj ├── tests ├── testthat.R └── testthat │ └── test-microbial.R └── vignettes └── microbial.Rmd /.travis.yml: -------------------------------------------------------------------------------- 1 | #---------------------------------------------------------------- 2 | # Travis-CI configuration for R packages 3 | # 4 | # REFERENCES: 5 | # * Travis CI: https://docs.travis-ci.com/user/languages/r# 6 | # YAML validated using http://www.yamllint.com/ 7 | #---------------------------------------------------------------- 8 | language: r 9 | sudo: false 10 | cache: packages 11 | warnings_are_errors: false 12 | r_check_args: --as-cran 13 | r: 14 | - bioc-devel 15 | 16 | cache: packages 17 | bioc_required: true 18 | bioc_use_devel: true 19 | latex: false 20 | 21 | matrix: 22 | include: 23 | - os: osx 24 | r_check_args: '--ignore-vignettes' 25 | r_build_args: '--no-build-vignettes' 26 | - dist: linux 27 | r_check_args: '--ignore-vignettes' 28 | r_build_args: '--no-build-vignettes' 29 | -------------------------------------------------------------------------------- /DESCRIPTION: -------------------------------------------------------------------------------- 1 | Package: microbial 2 | Type: Package 3 | Title: Do 16s Data Analysis and Generate Figures 4 | Version: 0.0.22 5 | Authors@R: c(person("Kai","Guo",email = "guokai8@gmail.com", 6 | role = c("aut", "cre") 7 | ), 8 | person("Pan","Gao",role = "aut")) 9 | Description: Provides functions to enhance the available 10 | statistical analysis procedures in R by providing simple functions to 11 | analysis and visualize the 16S rRNA data.Here we present a tutorial 12 | with minimum working examples to demonstrate usage and dependencies. 13 | License: GPL-3 14 | Depends: R (>= 3.5.0) 15 | Imports: 16 | dplyr, 17 | plyr, 18 | magrittr, 19 | broom, 20 | phyloseq, 21 | vegan, 22 | rlang, 23 | ggplot2, 24 | ggpubr, 25 | DESeq2, 26 | SummarizedExperiment, 27 | S4Vectors, 28 | rstatix, 29 | tidyr, 30 | phangorn, 31 | randomForest, 32 | edgeR, 33 | testthat 34 | Encoding: UTF-8 35 | LazyData: true 36 | Suggests: markdown,dada2,rmarkdown,knitr,tools,Biostrings, DECIPHER, MASS 37 | VignetteBuilder: knitr 38 | biocViews: Software,GraphAndNetwork 39 | RoxygenNote: 7.1.1 40 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | -------------------------------------------------------------------------------- /NAMESPACE: -------------------------------------------------------------------------------- 1 | # Generated by roxygen2: do not edit by hand 2 | 3 | export(betadiv) 4 | export(betatest) 5 | export(biomarker) 6 | export(buildTree) 7 | export(difftest) 8 | export(distcolor) 9 | export(do_aov) 10 | export(do_ttest) 11 | export(do_wilcox) 12 | export(glmr) 13 | export(ldamarker) 14 | export(lightcolor) 15 | export(normalize) 16 | export(otu_table) 17 | export(phy_tree) 18 | export(plotLDA) 19 | export(plotalpha) 20 | export(plotbar) 21 | export(plotbeta) 22 | export(plotdiff) 23 | export(plotmarker) 24 | export(plotquality) 25 | export(preRef) 26 | export(prefilter) 27 | export(processSeq) 28 | export(psmelt) 29 | export(richness) 30 | export(sample_data) 31 | export(subset_samples) 32 | export(subset_taxa) 33 | export(tax_table) 34 | importFrom(DESeq2,DESeq) 35 | importFrom(DESeq2,DESeqDataSetFromMatrix) 36 | importFrom(DESeq2,counts) 37 | importFrom(DESeq2,estimateDispersions) 38 | importFrom(DESeq2,estimateSizeFactors) 39 | importFrom(DESeq2,results) 40 | importFrom(DESeq2,varianceStabilizingTransformation) 41 | importFrom(S4Vectors,DataFrame) 42 | importFrom(SummarizedExperiment,assay) 43 | importFrom(broom,tidy) 44 | importFrom(dplyr,bind_rows) 45 | importFrom(dplyr,do) 46 | importFrom(dplyr,filter) 47 | importFrom(dplyr,group_by) 48 | importFrom(dplyr,group_by_at) 49 | importFrom(dplyr,left_join) 50 | importFrom(dplyr,mutate) 51 | importFrom(dplyr,one_of) 52 | importFrom(dplyr,pull) 53 | importFrom(dplyr,select) 54 | importFrom(dplyr,summarise) 55 | importFrom(dplyr,summarize) 56 | importFrom(dplyr,ungroup) 57 | importFrom(dplyr,vars) 58 | importFrom(edgeR,calcNormFactors) 59 | importFrom(ggplot2,aes) 60 | importFrom(ggplot2,aes_string) 61 | importFrom(ggplot2,coord_flip) 62 | importFrom(ggplot2,element_blank) 63 | importFrom(ggplot2,element_text) 64 | importFrom(ggplot2,geom_bar) 65 | importFrom(ggplot2,geom_point) 66 | importFrom(ggplot2,ggplot) 67 | importFrom(ggplot2,scale_color_manual) 68 | importFrom(ggplot2,scale_fill_manual) 69 | importFrom(ggplot2,scale_y_continuous) 70 | importFrom(ggplot2,stat_ellipse) 71 | importFrom(ggplot2,theme) 72 | importFrom(ggplot2,theme_light) 73 | importFrom(ggplot2,xlab) 74 | importFrom(ggplot2,ylab) 75 | importFrom(ggpubr,facet) 76 | importFrom(ggpubr,ggboxplot) 77 | importFrom(ggpubr,ggdotchart) 78 | importFrom(ggpubr,ggdotplot) 79 | importFrom(ggpubr,ggviolin) 80 | importFrom(ggpubr,stat_pvalue_manual) 81 | importFrom(magrittr,"%>%") 82 | importFrom(phangorn,NJ) 83 | importFrom(phangorn,dist.ml) 84 | importFrom(phangorn,optim.pml) 85 | importFrom(phangorn,phyDat) 86 | importFrom(phangorn,pml) 87 | importFrom(phangorn,pml.control) 88 | importFrom(phyloseq,'tax_table<-') 89 | importFrom(phyloseq,`otu_table<-`) 90 | importFrom(phyloseq,distance) 91 | importFrom(phyloseq,estimate_richness) 92 | importFrom(phyloseq,get_taxa_unique) 93 | importFrom(phyloseq,nsamples) 94 | importFrom(phyloseq,ordinate) 95 | importFrom(phyloseq,otu_table) 96 | importFrom(phyloseq,phyloseq) 97 | importFrom(phyloseq,prune_taxa) 98 | importFrom(phyloseq,psmelt) 99 | importFrom(phyloseq,sample_data) 100 | importFrom(phyloseq,subset_taxa) 101 | importFrom(phyloseq,t) 102 | importFrom(phyloseq,tax_table) 103 | importFrom(phyloseq,taxa_are_rows) 104 | importFrom(phyloseq,taxa_sums) 105 | importFrom(phyloseq,transform_sample_counts) 106 | importFrom(plyr,ddply) 107 | importFrom(randomForest,importance) 108 | importFrom(randomForest,randomForest) 109 | importFrom(rlang,`!!`) 110 | importFrom(rstatix,anova_test) 111 | importFrom(rstatix,t_test) 112 | importFrom(rstatix,wilcox_test) 113 | importFrom(stats,as.formula) 114 | importFrom(stats,binomial) 115 | importFrom(stats,glm) 116 | importFrom(stats,kruskal.test) 117 | importFrom(stats,p.adjust) 118 | importFrom(stats,reorder) 119 | importFrom(stats,update) 120 | importFrom(tidyr,gather) 121 | importFrom(tidyr,spread) 122 | importFrom(utils,download.file) 123 | importFrom(utils,head) 124 | importFrom(utils,read.delim) 125 | importFrom(utils,write.table) 126 | importFrom(vegan,adonis) 127 | importFrom(vegan,diversity) 128 | importFrom(vegan,rarefy) 129 | importFrom(vegan,specnumber) 130 | -------------------------------------------------------------------------------- /R/Functions.R: -------------------------------------------------------------------------------- 1 | #' Download the reference database 2 | #' @importFrom utils download.file 3 | #' @param ref_db the reference database 4 | #' @param path path for the database 5 | #' @return the path of the database 6 | #' @author Kai Guo 7 | #' @examples 8 | #' \donttest{ 9 | #' preRef(ref_db="silva",path=tempdir()) 10 | #' } 11 | #' @export 12 | preRef<-function(ref_db,path="."){ 13 | if (ref_db == "rdp"){ 14 | ifelse(!file.exists(paste0(path,"/rdp_train_set_16.fa.gz")), 15 | download.file(url = "https://zenodo.org/record/801828/files/rdp_train_set_16.fa.gz?download=1", 16 | destfile = file.path(paste0(path, "/rdp_train_set_16.fa.gz")), 17 | method = "auto"), 18 | FALSE); 19 | ifelse(!file.exists(paste0(path,"/rdp_species_assignment_16.fa.gz")), 20 | download.file(url = "https://zenodo.org/record/801828/files/rdp_species_assignment_16.fa.gz?download=1", 21 | destfile = file.path(paste0(path, "/rdp_species_assignment_16.fa.gz")), 22 | method = "auto"), 23 | FALSE); 24 | message("Database: ") 25 | message(paste0(path,"/rdp_train_set_16.fa.gz")) 26 | message(paste0(path, "/rdp_species_assignment_16.fa.gz")) 27 | } else if (ref_db == "silva"){ 28 | ifelse(!file.exists(paste0(path,"/silva_nr99_v138_train_set.fa.gz")), 29 | download.file(url = "https://zenodo.org/record/4587955/files/silva_nr99_v138.1_train_set.fa.gz?download=1", 30 | destfile = file.path(paste0(path, "/silva_nr99_v138_train_set.fa.gz")), 31 | method = "auto"), 32 | FALSE); 33 | ifelse(!file.exists(paste0(path,"/silva_species_assignment_v138.fa.gz?")), 34 | download.file(url = 'https://zenodo.org/record/4587955/files/silva_species_assignment_v138.1.fa.gz?download=1', 35 | destfile = file.path(paste0(path,"/silva_species_assignment_v138.fa.gz")), 36 | method = 'auto'), 37 | FALSE); 38 | message("Database: ") 39 | message(paste0(path,"/silva_nr99_v138_train_set.fa.gz")) 40 | message(paste0(path, "/silva_species_assignment_v138.fa.gz")) 41 | } else { 42 | ifelse(!dir.exists(paste0(path,"/gg_13_8_train_set_97.fa.gz")), 43 | download.file(url = "https://zenodo.org/record/158955/files/gg_13_8_train_set_97.fa.gz?download=1", 44 | destfile = file.path(paste0(path, "/gg_13_8_train_set_97.fa.gz")), 45 | method = "auto"), 46 | FALSE); 47 | message("Database: ") 48 | message(paste0(path,"/gg_13_8_train_set_97.fa.gz")) 49 | } 50 | } 51 | 52 | #' filter the phyloseq 53 | #' @importFrom phyloseq subset_taxa prune_taxa otu_table taxa_are_rows tax_table 54 | #' @importFrom phyloseq taxa_sums get_taxa_unique 55 | #' @importFrom phyloseq 'tax_table<-' 56 | #' @importFrom plyr ddply 57 | #' @param physeq A \code{phyloseq} object containing merged information of abundance, 58 | #' taxonomic assignment, sample data including the measured variables and categorical information 59 | #' of the samples, and / or phylogenetic tree if available. 60 | #' @param min Numeric, the threshold for mininal Phylum shown in samples 61 | #' @param perc Numeric, input the percentage of samples for which to filter low counts. 62 | #' @examples 63 | #' \donttest{ 64 | #' data("Physeq") 65 | #' physeqs<-prefilter(physeq) 66 | #' } 67 | #' @return filter phyloseq object 68 | #' @author Kai Guo 69 | #' @export 70 | 71 | prefilter<-function(physeq,min=10,perc=0.05){ 72 | ##remove "" in phylum level 73 | ps <- subset_taxa(physeq, !is.na(Phylum) & !Phylum %in% c("", "uncharacterized")) 74 | # Compute prevalence of each feature, store as data.frame 75 | prevdf = apply(X = otu_table(ps), 76 | MARGIN = ifelse(taxa_are_rows(ps), yes = 1, no = 2), 77 | FUN = function(x){sum(x > 0)}) 78 | # Add taxonomy and total read counts to this data.frame 79 | prevdf = data.frame(Prevalence = prevdf, 80 | TotalAbundance = taxa_sums(ps), 81 | tax_table(ps)) 82 | #compute the total and the average prevalences of the features in each phylum 83 | prer<-ddply(prevdf, "Phylum", function(df1){cbind(mean(df1$Prevalence),sum(df1$Prevalence))}) 84 | colnames(prer)[2:3]<-c("average","total") 85 | filterPhyla<-prer$Phylum[which(prer$total/prer$average= prevalenceThreshold)] 94 | prevdfr<-prevdf1[keepTaxa,] 95 | psf = prune_taxa(keepTaxa, ps) 96 | } 97 | 98 | #' @title calculat the richness for the phyloseq object 99 | #' @importFrom phyloseq estimate_richness otu_table 100 | #' @importFrom vegan rarefy 101 | #' @importFrom vegan diversity 102 | #' @importFrom vegan specnumber 103 | #' @importFrom phyloseq otu_table 104 | #' @param physeq A \code{phyloseq} object containing merged information of abundance, 105 | #' taxonomic assignment, sample data including the measured variables and categorical information 106 | #' of the samples, and / or phylogenetic tree if available. 107 | #' @param method A list of character strings specifying \code{method} to be used to calculate for alpha diversity 108 | #' in the data. Available methods are: "Observed","Chao1","ACE","Richness", "Fisher", "Simpson", "Shannon", "Evenness","InvSimpson". 109 | #' @examples 110 | #' { 111 | #' data("Physeq") 112 | #' rich <-richness(physeq,method=c("Simpson", "Shannon")) 113 | #' } 114 | #' @return data.frame of alpha diversity 115 | #' @export 116 | #' @author Kai Guo 117 | richness<-function(physeq,method=c("Observed","Simpson", "Shannon")){ 118 | method<-as.character(sapply(method,function(x)simpleCap(x),simplify = T)) 119 | method<- match.arg(method,c("Observed","Chao1","ACE","Richness", "Fisher", "Simpson", "Shannon", "Evenness","InvSimpson"), several.ok = TRUE) 120 | df <- estimate_richness(physeq) 121 | if(!isTRUE(taxa_are_rows(physeq))){ 122 | tab<-t(otu_table(physeq)) 123 | }else{ 124 | tab<-otu_table(physeq) 125 | } 126 | rownames(df)<-colnames(tab) 127 | if("Evenness"%in%method){ 128 | ta<-as.data.frame(t(tab)) 129 | H<-diversity(ta) 130 | S <- specnumber(ta) 131 | J <- H/log(S) 132 | df_J<-data.frame(Evenness=J) 133 | df<-cbind(df,df_J) 134 | } 135 | if("Richness"%in%method){ 136 | ta<-as.data.frame(t(tab)) 137 | R<- rarefy(ta,min(rowSums(ta))) 138 | df_R<-data.frame(Richness=R) 139 | df<-cbind(df,df_R) 140 | } 141 | df<-df[,method,drop=FALSE] 142 | return(df) 143 | } 144 | #' @title calcaute beta diversity 145 | #' @importFrom phyloseq ordinate 146 | #' @param physeq A \code{phyloseq} object containing merged information of abundance, 147 | #' taxonomic assignment, sample data including the measured variables and categorical information 148 | #' of the samples, and / or phylogenetic tree if available. 149 | #' @param method A character string specifying ordination method. All methods available to the \code{ordinate} function 150 | #' of \code{phyloseq} are acceptable here as well. 151 | #' @param distance A string character specifying dissimilarity index to be used in calculating pairwise distances (Default index is "bray".). 152 | #' "unifrac","wunifrac","manhattan", "euclidean", "canberra", "bray", "kulczynski", "jaccard", "gower", "altGower", 153 | #' "morisita", "horn", "mountford", "raup" , "binomial", "chao", "cao" or "mahalanobis". 154 | #' @export 155 | #' @author Kai Guo 156 | #' @examples 157 | #' { 158 | #' data("Physeq") 159 | #' phy<-normalize(physeq) 160 | #' res <- betadiv(phy) 161 | #' } 162 | #' @return list with beta diversity data.frame and PCs 163 | betadiv<-function(physeq,distance="bray",method="PCoA"){ 164 | beta<-ordinate(physeq,method = method,distance = distance) 165 | pcs<-beta$values[,2] 166 | df<-beta$vectors 167 | return(list(beta=df,PCs=pcs)) 168 | } 169 | #' @title PERMANOVA test for phyloseq 170 | #' @importFrom phyloseq distance 171 | #' @importFrom vegan adonis 172 | #' @importFrom tidyr gather 173 | #' @importFrom dplyr group_by 174 | #' @importFrom dplyr do 175 | #' @importFrom magrittr %>% 176 | #' @param physeq A \code{phyloseq} object containing merged information of abundance, 177 | #' taxonomic assignment, sample data including the measured variables and categorical information 178 | #' of the samples, and / or phylogenetic tree if available. 179 | #' @param distance A string character specifying dissimilarity index to be used in calculating pairwise distances (Default index is "bray".). 180 | #' "unifrac","wunifrac","manhattan", "euclidean", "canberra", "bray", "kulczynski", "jaccard", "gower", "altGower", 181 | #' "morisita", "horn", "mountford", "raup" , "binomial", "chao", "cao" or "mahalanobis". 182 | #' @param group (Required). Character string specifying name of a categorical variable that is preferred for grouping the information. 183 | #' information. 184 | #' @examples 185 | #'{ 186 | #' data("Physeq") 187 | #' phy<-normalize(physeq) 188 | #' beta <-betatest(phy,group="SampleType") 189 | #' } 190 | #' @return PERMANOVA test result 191 | #' @export 192 | #' @author Kai Guo 193 | betatest<-function(physeq,group,distance="bray"){ 194 | message("Do PERMANOVA for: ",group) 195 | dist<-distance(physeq,method = distance) 196 | tab <- as(sample_data(physeq),"data.frame") 197 | tab<-tab[,group,drop=F] 198 | res<-NULL 199 | if(length(group)>1){ 200 | res<- tab%>%gather(Group,val)%>%group_by(Group)%>%do(as.data.frame(adonis(dist~val,.)$aov.tab)) 201 | }else{ 202 | tab$Group <- tab[,group] 203 | res<-as.data.frame(adonis(dist~Group,tab)$aov.tab) 204 | } 205 | return(as.data.frame(res)) 206 | } 207 | 208 | #' Normalize the phyloseq object with different methods 209 | #' @importFrom phyloseq transform_sample_counts sample_data 210 | #' @importFrom phyloseq taxa_are_rows nsamples otu_table psmelt 211 | #' @importFrom DESeq2 DESeqDataSetFromMatrix estimateSizeFactors 212 | #' @importFrom DESeq2 estimateDispersions varianceStabilizingTransformation 213 | #' @importFrom SummarizedExperiment assay 214 | #' @importFrom S4Vectors DataFrame 215 | #' @importFrom edgeR calcNormFactors 216 | #' @param physeq A \code{phyloseq} object containing merged information of abundance, 217 | #' taxonomic assignment, sample data including the measured variables and categorical information 218 | #' of the samples, and / or phylogenetic tree if available. 219 | #' @param method A list of character strings specifying \code{method} to be used to normalize the phyloseq object 220 | #' Available methods are: "relative","TMM","vst","log2". 221 | #' @param group group (DESeq2). A character string specifying the name of a categorical variable containing grouping information. 222 | #' @param table return a data.frame or not 223 | #' @examples 224 | #' { 225 | #' data("Physeq") 226 | #' phy<-normalize(physeq) 227 | #' } 228 | #' @return phyloseq object with normalized data 229 | #' @author Kai Guo 230 | #' @export 231 | normalize<-function(physeq,group,method="relative",table=FALSE){ 232 | if(!taxa_are_rows(physeq)){ 233 | physeq<-t(physeq) 234 | } 235 | otu<-as(otu_table(physeq),"matrix") 236 | tab<-as(sample_data(physeq),"data.frame") 237 | group<-tab[,group] 238 | if(method=="vst"){ 239 | message("Normalization using DESeq2 varianceStabilizingTransformation method") 240 | otu <- otu+1 241 | condition=group 242 | dds = DESeqDataSetFromMatrix(otu, DataFrame(condition), ~ condition) 243 | dds = estimateSizeFactors(dds) 244 | dds = estimateDispersions(dds) 245 | vst <- varianceStabilizingTransformation(dds) 246 | otu_table(physeq) <- otu_table(assay(vst), taxa_are_rows=TRUE) 247 | } 248 | if(method=="relative"){ 249 | message("Normalization using relative method ") 250 | physeq<-transform_sample_counts(physeq,function(x)x/sum(x)) 251 | } 252 | if(method=="TMM"){ 253 | # modified from https://github.com/aametwally/MetaLonDA/blob/master/R/Normalization. 254 | message("Normalization using TMM method ") 255 | otu = otu + 1 256 | # Check `group` argument 257 | factors = calcNormFactors(otu, method="TMM") 258 | eff.lib.size = colSums(otu) * factors 259 | ref.lib.size = mean(eff.lib.size) #Use the mean of the effective library sizes as a reference library size 260 | count = sweep(otu, MARGIN = 2, eff.lib.size, "/") * ref.lib.size 261 | otu_table(physeq) <- otu_table(count, taxa_are_rows=TRUE) 262 | } 263 | if(method=="log2"){ 264 | message("Normalization using log2 of the RA method ") 265 | physeq<-transform_sample_counts(physeq,function(x)log2(x/sum(x)+1)) 266 | } 267 | if(isTRUE(table)){ 268 | physeq <- psmelt(physeq) 269 | } 270 | return(physeq) 271 | } 272 | #' @title Calculate differential bacteria with DESeq2 273 | #' @importFrom DESeq2 DESeqDataSetFromMatrix counts 274 | #' @importFrom phyloseq otu_table taxa_are_rows 275 | #' @importFrom phyloseq sample_data 276 | #' @importFrom DESeq2 results DESeq 277 | #' @importFrom stats as.formula 278 | #' @param physeq A \code{phyloseq} object containing merged information of abundance, 279 | #' taxonomic assignment, sample data including the measured variables and categorical information 280 | #' of the samples, and / or phylogenetic tree if available. 281 | #' @param group group (DESeq2). A character string specifying the name of a categorical variable containing grouping information. 282 | #' @param ref reference group 283 | #' @param pvalue pvalue threshold for significant results 284 | #' @param padj adjust p value threshold for significant results 285 | #' @param log2FC log2 Fold Change threshold 286 | #' @param gm_mean TRUE/FALSE calculate geometric means prior to estimate size factors 287 | #' @param fitType either "parametric", "local", or "mean" for the type of fitting of dispersions to the mean intensity. 288 | #' @param quiet whether to print messages at each step 289 | #' @examples 290 | #' \donttest{ 291 | #' data("Physeq") 292 | #' res <- difftest(physeq,group="group") 293 | #' } 294 | #' @return datafame with differential test with DESeq2 295 | #' @author Kai Guo 296 | #' @export 297 | #' 298 | difftest<-function(physeq,group,ref=NULL,pvalue=0.05,padj=NULL,log2FC=0,gm_mean=TRUE,fitType="local",quiet=FALSE){ 299 | if(!taxa_are_rows(physeq)){ 300 | physeq<-t(physeq) 301 | } 302 | otu <- as(otu_table(physeq),"matrix") 303 | tax <- as.data.frame(as.matrix(tax_table(physeq))) 304 | colData<-as(sample_data(physeq),"data.frame") 305 | colData$condition<-colData[,group] 306 | contrasts<-levels(factor(unique(colData$condition))) 307 | if(!is.null(ref)){ 308 | contrasts <- c(setdiff(contrasts,ref),ref) 309 | } 310 | if(isTRUE(gm_mean)){ 311 | countData<-round(otu, digits = 0) 312 | }else{ 313 | countData<-round(otu, digits = 0)+1 314 | } 315 | dds <- DESeqDataSetFromMatrix(countData, colData, as.formula(~condition)) 316 | if(isTRUE(gm_mean)){ 317 | geoMeans = apply(counts(dds), 1, gm_mean) 318 | dds = estimateSizeFactors(dds, geoMeans = geoMeans) 319 | } 320 | dds <- DESeq(dds, fitType=fitType) 321 | res <- results(dds,contrast=c("condition",contrasts),cooksCutoff = FALSE) 322 | res_tax = cbind(as.data.frame(res), as.matrix(countData[rownames(res), ])) 323 | if(!is.null(padj)){ 324 | pval<-padj 325 | sig <- rownames(subset(res,padjlog2FC)) 326 | }else{ 327 | pval<-pvalue 328 | sig <- rownames(subset(res,pvaluelog2FC)) 329 | } 330 | res_tax$Significant<- "No" 331 | res_tax$Significant <- ifelse(rownames(res_tax) %in% sig, "Yes", "No") 332 | res_tax <- cbind(res_tax, tax[rownames(res),]) 333 | return(as.data.frame(res_tax)) 334 | } 335 | 336 | #' @title Identify biomarker by using randomForest method 337 | #' @importFrom phyloseq taxa_are_rows otu_table sample_data t 338 | #' @importFrom randomForest randomForest importance 339 | #' @importFrom tidyr gather 340 | #' @importFrom dplyr group_by filter 341 | #' @importFrom dplyr do 342 | #' @importFrom magrittr %>% 343 | #' @importFrom broom tidy 344 | #' @importFrom stats kruskal.test 345 | #' @param physeq A \code{phyloseq} object containing merged information of abundance, 346 | #' taxonomic assignment, sample data including the measured variables and categorical information 347 | #' of the samples, and / or phylogenetic tree if available. 348 | #' @param group group. A character string specifying the name of a categorical variable containing grouping information. 349 | #' @param ntree Number of trees to grow. This should not be set to too small a number, 350 | #' to ensure that every input row gets predicted at least a few times. 351 | #' @param pvalue pvalue threshold for significant results from kruskal.test 352 | #' @param normalize to normalize the data before analysis(TRUE/FALSE) 353 | #' @param method A list of character strings specifying \code{method} to be used to normalize the phyloseq object 354 | #' Available methods are: "relative","TMM","vst","log2". 355 | #' @examples 356 | #' \donttest{ 357 | #' data("Physeq") 358 | #' res <- biomarker(physeq,group="group") 359 | #' } 360 | #' @return data frame with significant biomarker 361 | #' @author Kai Guo 362 | #' @export 363 | biomarker<-function(physeq,group,ntree=500,pvalue=0.05,normalize=TRUE,method="relative"){ 364 | if(isTRUE(normalize)){ 365 | physeq<-normalize(physeq,method = method) 366 | } 367 | if(taxa_are_rows(physeq)){ 368 | physeq<-t(physeq) 369 | } 370 | tax <- as.data.frame(as.matrix(tax_table(physeq))) 371 | sam <- as(sample_data(physeq),"data.frame") 372 | tab <- as.data.frame(otu_table(physeq)) 373 | tab$group<-sam[,group] 374 | sel<-tab%>%gather(OTU,val,-group)%>%group_by(OTU)%>%do(tidy(kruskal.test(val~group,.)))%>% 375 | filter(p.value<0.05) 376 | data<-tab[,sel$OTU] 377 | #change the colnames in case only have number in the colname 378 | colnames(data)<-paste0("X",colnames(data)) 379 | data$group<-tab$group 380 | data$group<-factor(data$group) 381 | val<-randomForest(group ~ ., data=data, importance=TRUE, proximity=TRUE,ntree=ntree) 382 | print(val) 383 | imp<- importance(val) 384 | res<-data.frame(row.names=NULL,OTU=sub('X','',rownames(imp)), 385 | Value=abs(as.numeric(imp[,"MeanDecreaseAccuracy"])), 386 | Index=rep("Mean Decrease Accuracy",dim(imp)[1])) 387 | #Rearrange the features in terms of importance for ggplot2 by changing factor levels 388 | res$rank <- rank(res$Value, ties.method = "min") 389 | res$rank <- max(res$rank)-res$rank+1 390 | res<-cbind(res,tax[res$OTU,]) 391 | res<-res[order(res$rank),] 392 | res 393 | } 394 | #' Identify biomarker by using LEfSe method 395 | #' @importFrom phyloseq taxa_are_rows otu_table sample_data 396 | #' @importFrom phyloseq `otu_table<-` 397 | #' @importFrom dplyr group_by summarize do left_join 398 | #' @importFrom dplyr ungroup bind_rows mutate 399 | #' @importFrom broom tidy 400 | #' @importFrom magrittr %>% 401 | #' @importFrom stats p.adjust 402 | #' 403 | #' @param physeq A \code{phyloseq} object containing merged information of abundance, 404 | #' taxonomic assignment, sample data including the measured variables and categorical information 405 | #' of the samples, and / or phylogenetic tree if available. 406 | #' @param group group. A character string specifying the name of a categorical variable containing grouping information. 407 | #' @param pvalue pvalue threshold for significant results from kruskal.test 408 | #' @param normalize to normalize the data before analysis(TRUE/FALSE) 409 | #' @param method A list of character strings specifying \code{method} to be used to normalize the phyloseq object 410 | #' Available methods are: "relative","TMM","vst","log2". 411 | #' @examples 412 | #' \donttest{ 413 | #' data("Physeq") 414 | #' res <- ldamarker(physeq,group="group") 415 | #' } 416 | #' 417 | #' @author Kai Guo 418 | #' @export 419 | ldamarker<-function(physeq,group,pvalue=0.05,normalize=TRUE,method="relative"){ 420 | if(isTRUE(normalize)){ 421 | physeq<-normalize(physeq,method = method) 422 | # count per million *10e6 (CPM) 423 | otu_table(physeq)<-otu_table(physeq)*10e6 424 | } 425 | if(!taxa_are_rows(physeq)){ 426 | physeq<-t(physeq) 427 | } 428 | tax <- as.data.frame(as.matrix(tax_table(physeq))) 429 | sam<-as(sample_data(physeq),"data.frame") 430 | level<-colnames(tax) 431 | tab<-psmelt(physeq) 432 | otul <- lapply(1:length(level),function(i) { 433 | lvls <- level[1:i] 434 | lvl <- level[i] 435 | otu_lev <- tab 436 | otu_lev$tax <- do.call(paste,c(lapply(lvls,function(l) tab[[l]]),sep="|")) 437 | otu_lev$rank <- lvl 438 | otu_lev2 <- otu_lev %>% group_by(Sample,tax,rank) %>% 439 | summarize(seqs=sum(Abundance)) %>% ungroup() 440 | return(otu_lev2) 441 | }) 442 | otu <- bind_rows(otul) %>% 443 | mutate(tax=gsub("\\|","_",tax)) 444 | ### 445 | otu$group<-sam[otu$Sample,group] 446 | ### 447 | pvalues<-otu%>%group_by(rank,tax)%>%do(tidy(kruskal.test(seqs~group,.))) 448 | pvalues$p.adj<-p.adjust(pvalues$p.value, method ="fdr"); 449 | ## 450 | df<-pvalues%>%left_join(otu,by=c("tax"="tax")) 451 | dd<-df[df$p.value%left_join(resTable,by=c("tax"="tax")) 458 | return(resTable) 459 | } 460 | -------------------------------------------------------------------------------- /R/dada2.R: -------------------------------------------------------------------------------- 1 | #' Perform dada2 analysis 2 | #' @importFrom phyloseq phyloseq otu_table sample_data tax_table 3 | #' @importFrom utils read.delim write.table 4 | #' @param path working dir for the input reads 5 | #' @param truncLen (Optional). Default 0 (no truncation). Truncate reads after truncLen bases. Reads shorter than this are discarded. 6 | #' @param trimLeft (Optional). The number of nucleotides to remove from the start of each read. 7 | #' @param trimRight (Optional). Default 0. The number of nucleotides to remove from the end of each read. 8 | #' If both truncLen and trimRight are provided, truncation will be performed after trimRight is enforced. 9 | #' @param sample_info (Optional).sample information for the sequence 10 | #' @param minLen (Optional). Default 20. Remove reads with length less than minLen. minLen is enforced after trimming and truncation. 11 | #' @param maxLen Optional). Default Inf (no maximum). Remove reads with length greater than maxLen. maxLen is enforced before trimming and truncation. 12 | #' @param train_data (Required).training database 13 | #' @param train_species (Required). species database 14 | #' @param outpath (Optional).the path for the filtered reads and th out table 15 | #' @param saveobj (Optional).Default FALSE. save the phyloseq object output. 16 | #' @param buildtree build phylogenetic tree or not(default: FALSE) 17 | #' @param verbose (Optional). Default TRUE. Print verbose text output. 18 | #' @author Kai Guo 19 | #' @return list include count table, summary table, taxonomy information and phyloseq object 20 | #' @export 21 | processSeq <- function(path=".", 22 | truncLen = c(0, 0), 23 | trimLeft=0, 24 | trimRight=0, 25 | minLen=20, 26 | maxLen=Inf, 27 | sample_info=NULL, 28 | train_data="silva_nr99_v138_train_set.fa.gz", 29 | train_species="silva_species_assignment_v138.fa.gz", 30 | outpath=NULL, 31 | saveobj=FALSE, 32 | buildtree=FALSE, 33 | verbose=TRUE){ 34 | OS<-.Platform$OS.type 35 | if(OS=="windows"){ 36 | multithread<-FALSE 37 | }else{ 38 | multithread<-TRUE 39 | } 40 | fnFs <- sort(list.files(path, pattern="R1", full.names = TRUE)) 41 | fnRs <- sort(list.files(path, pattern="R2", full.names = TRUE)) 42 | message("check the filename ......") 43 | if(any(grepl('R1|R2',fnFs)==FALSE)){ 44 | stop("All fastq name should be either contain R1 or R2 \n") 45 | } 46 | sample.names <-sub('@@@@.*','',sub('(\\.|_)R(1|2)','@@@@',basename(fnFs))) 47 | if(sum(duplicated(sample.names))>=1){ 48 | stop('The fastq filenames are not unique!\n') 49 | } 50 | #filter and trim; 51 | if(isTRUE(verbose)){ 52 | message("Filtering......"); 53 | } 54 | if(is.null(outpath)){ 55 | outpath<-path 56 | } 57 | ifelse(!dir.exists(paste0(outpath,"/filtered")),dir.create(file.path(outpath,"filtered"),recursive=TRUE),FALSE); 58 | filtFs <- file.path(outpath, "filtered", paste0(sample.names, "_F_filt.fastq.gz")) 59 | filtRs <- file.path(outpath, "filtered", paste0(sample.names, "_R_filt.fastq.gz")) 60 | out <- dada2::filterAndTrim(fnFs, filtFs, fnRs, filtRs, truncLen=truncLen,trimLeft=trimLeft,trimRight=trimRight, 61 | maxN=0, maxEE=c(2,2), truncQ=2, rm.phix=TRUE,minLen=minLen,maxLen = maxLen, 62 | compress=TRUE, multithread=multithread) # On Windows set multithread=FALSE 63 | if(isTRUE(verbose)){ 64 | message("Learning error......") 65 | } 66 | errF <- dada2::learnErrors(filtFs, multithread=multithread) 67 | errR <- dada2::learnErrors(filtRs, multithread=multithread) 68 | if(isTRUE(verbose)){ 69 | message("Dereplicating......") 70 | } 71 | derepFs <- dada2::derepFastq(filtFs, verbose=FALSE) 72 | derepRs <- dada2::derepFastq(filtRs, verbose=FALSE) 73 | # Name the derep-class objects by the sample names 74 | names(derepFs) <- sample.names 75 | names(derepRs) <- sample.names 76 | if(isTRUE(verbose)){ 77 | message("Error correction......") 78 | } 79 | dadaFs <- dada2::dada(derepFs, err=errF, multithread=TRUE) 80 | dadaRs <- dada2::dada(derepRs, err=errR, multithread=TRUE) 81 | if(isTRUE(verbose)){ 82 | message("Mergering.......") 83 | } 84 | mergers <- dada2::mergePairs(dadaFs, derepFs, dadaRs, derepRs, verbose=FALSE) 85 | if(isTRUE(verbose)){ 86 | message("Making table.......") 87 | } 88 | seqtab <- dada2::makeSequenceTable(mergers) 89 | if(isTRUE(verbose)){ 90 | message("Remove chimeras.......") 91 | } 92 | seqtab.nochim <- dada2::removeBimeraDenovo(seqtab, method="consensus", multithread=TRUE, verbose=FALSE) 93 | asv_seqs <- colnames(seqtab.nochim) 94 | asv_headers <- vector(dim(seqtab.nochim)[2], mode="character") 95 | for (i in 1:dim(seqtab.nochim)[2]) { 96 | asv_headers[i] <- paste(">ASV", i, sep="_") 97 | } 98 | getN <- function(x) sum(dada2::getUniques(x)) 99 | track <- cbind(out, sapply(dadaFs, getN), sapply(dadaRs, getN), sapply(mergers, getN), rowSums(seqtab.nochim)) 100 | # If processing a single sample, remove the sapply calls: e.g. replace sapply(dadaFs, getN) with getN(dadaFs) 101 | colnames(track) <- c("input", "filtered", "denoisedF", "denoisedR", "merged", "nonchim") 102 | rownames(track) <- sample.names 103 | # count table: 104 | asv_count <- t(seqtab.nochim) 105 | rownames(asv_count) <- sub(">", "", asv_headers) 106 | ### set back to the previous work dir 107 | if(isTRUE(verbose)){ 108 | message("Write out the count table.......") 109 | } 110 | write.table(asv_count,paste0(outpath, "/ASVs_counts.txt"), sep="\t", quote=F) 111 | if(isTRUE(verbose)){ 112 | message("Assign taxonomy........") 113 | } 114 | if(is.null(train_data)|is.null(train_species)){ 115 | stop("Please specify the path for the sliva database......\n ") 116 | }else{ 117 | taxa <- dada2::assignTaxonomy(seqtab.nochim, train_data, multithread=multithread) 118 | taxa <- dada2::addSpecies(taxa, train_species) 119 | ### 120 | taxtab<-unname(taxa) 121 | ### get sequence and do phylo anaylsis 122 | seqs <- dada2::getSequences(seqtab.nochim) 123 | names(seqs) <- seqs # This propagates to the tip labels of the tree 124 | if(isTRUE(verbose)){ 125 | message("write out sequence and taxonomy results") 126 | } 127 | # fasta: 128 | asv_fasta <- c(rbind(asv_headers, asv_seqs)) 129 | write(asv_fasta,paste0(outpath, "/ASVs.fa")) 130 | # tax table: 131 | asv_taxa <- taxa 132 | row.names(asv_taxa) <- sub(">", "", asv_headers) 133 | write.table(asv_taxa, paste0(outpath,"/ASVs_taxonomy.txt"), sep="\t", quote=F) 134 | } 135 | if(isTRUE(verbose)){ 136 | message("creating phyloseq object......") 137 | } 138 | if(!is.null(sample_info)){ 139 | if(is.character(sample_info)){ 140 | ext<-.checkfile(sample_info) 141 | if(ext=="txt"){ 142 | sampdf<-read.delim(sample_info,sep="\t",header = TRUE,row.names = 1) 143 | } 144 | if(ext=="csv"){ 145 | sampdf<-read.delim(sample_info,sep=",",header = TRUE,row.names = 1) 146 | } 147 | sampdf<-sampdf[rownames(seqtab.nochim),] 148 | }else{ 149 | sampdf<-sample_info 150 | sampdf<-sampdf[rownames(seqtab.nochim),] 151 | } 152 | }else{ 153 | sampdf<-data.frame(ID=colnames(asv_count)) 154 | rownames(sampdf)<-colnames(asv_count) 155 | } 156 | if(isTRUE(buildtree)){ 157 | tree <- buildTree(seqs) 158 | } 159 | ps <- phyloseq(otu_table(asv_count, taxa_are_rows=T), 160 | sample_data(sampdf), 161 | tax_table(asv_taxa)) 162 | if(isTRUE(saveobj)){ 163 | save(ps,file=paste0(outpath,"phyloseq.rdata"),compress=TRUE) 164 | } 165 | res<-list(track=track,count=asv_count,taxonomy=asv_taxa,physeq=ps) 166 | return(res) 167 | } 168 | -------------------------------------------------------------------------------- /R/data.R: -------------------------------------------------------------------------------- 1 | ################################################################################ 2 | #' The physeq data was modified from the (Data) Global patterns of 16S rRNA diversity at a depth of millions of sequences per sample (2011) 3 | #' 4 | #' Published in PNAS in early 2011. This work compared the microbial 5 | #' communities from 25 environmental samples and three known ``mock communities'' 6 | #' -- a total of 9 sample types -- at a depth averaging 3.1 million reads per sample. 7 | #' Authors were able to reproduce diversity patterns seen in many other 8 | #' published studies, while also invesitigating technical issues/bias by 9 | #' applying the same techniques to simulated microbial communities of known 10 | #' 11 | #' @references 12 | #' Caporaso, J. G., et al. (2011). 13 | #' Global patterns of 16S rRNA diversity at a depth of millions of sequences per sample. 14 | #' PNAS, 108, 4516-4522. 15 | #' PMCID: PMC3063599 16 | #' 17 | #' @name data-physeq 18 | #' @aliases physeq 19 | #' @docType data 20 | #' @keywords data 21 | #' @examples 22 | #' data(Physeq) 23 | ################################################################################ 24 | NA 25 | -------------------------------------------------------------------------------- /R/glmr.R: -------------------------------------------------------------------------------- 1 | #' @title Do the generalized linear model regression 2 | #' @importFrom phyloseq taxa_are_rows otu_table sample_data 3 | #' @importFrom broom tidy 4 | #' @importFrom stats binomial glm 5 | #' @param physeq phyloseq object 6 | #' @param group the group factor to regression 7 | #' @param factors a vector to indicate adjuested factors 8 | #' @param ref the reference group 9 | #' @param family binomial() or gaussian() 10 | #' @examples 11 | #' \donttest{ 12 | #' data("Physeq") 13 | #' phy<-normalize(physeq) 14 | #' fit <-glmr(phy,group="SampleType") 15 | #' } 16 | #' @export 17 | #' @author Kai Guo 18 | 19 | glmr<-function(physeq,group,factors=NULL,ref=NULL,family=binomial(link = "logit")){ 20 | if (!taxa_are_rows(physeq)) { 21 | physeq <- t(physeq) 22 | } 23 | otu <- as(otu_table(physeq), "matrix") 24 | otu <- as.data.frame(t(otu)) 25 | colnames(otu)<-paste0('ASV_',colnames(otu)) 26 | samd <- sample_data(physeq)[,c(group,factors)] 27 | dd <- cbind(samd[rownames(otu),],otu) 28 | if(!is.null(ref)){ 29 | level <- unique(dd[,group]) 30 | level <- c(ref,setdiff(level,ref)) 31 | }else{ 32 | level <- unique(dd[,group]) 33 | } 34 | dd[,group]<-factor(dd[,group],levels = level) 35 | cat('##########################################\n') 36 | cat('Do the generalized linear model regression with ',factors,'adjusted',"\n") 37 | cat(paste0(group,"~",paste0(factors,collapse="+"),"+x"),"\n") 38 | cat('##########################################\n') 39 | rr<-lapply(colnames(otu)[1:50],function(x)tidy(glm(as.formula(paste0(group,"~",paste0(factors,collapse="+"),"+",x)),data=dd,family=family))) 40 | names(rr)<- sub('ASV_','',colnames(otu)[1:50]) 41 | res <- do.call(rbind,rr) 42 | res <- res[grep('ASV_',res$term),] 43 | res$term<-sub('ASV_','',res$term) 44 | res$padj <- p.adjust(res$p.value,method="BH") 45 | res <- res[order(res$padj),] 46 | return(res) 47 | } 48 | -------------------------------------------------------------------------------- /R/misc.R: -------------------------------------------------------------------------------- 1 | simpleCap <- function(x) { 2 | s <- strsplit(x, " ")[[1]] 3 | paste(toupper(substring(s, 1,1)), substring(s, 2), 4 | sep="", collapse=" ") 5 | } 6 | 7 | #' light colors for making figures 8 | #' @author Kai Guo 9 | #' @export 10 | lightcolor<-c('#E5D2DD', '#53A85F', '#F1BB72', '#F3B1A0', '#D6E7A3', '#57C3F3', '#476D87', 11 | '#E95C59', '#E59CC4', '#AB3282', '#23452F', '#BD956A', '#8C549C', '#585658', 12 | '#9FA3A8', '#E0D4CA', '#5F3D69', '#C5DEBA', '#58A4C3', '#E4C755', '#F7F398', 13 | '#AA9A59', '#E63863', '#E39A35', '#C1E6F3', '#6778AE', '#91D0BE', '#B53E2B', 14 | '#712820', '#DCC1DD', '#CCE0F5', '#CCC9E6', '#625D9E', '#68A180', '#3A6963', 15 | '#968175','#e6194b', '#3cb44b', '#ffe119', '#4363d8','#f58231', '#911eb4', 16 | '#46f0f0', '#f032e6', '#bcf60c', 17 | '#fabebe', '#008080', '#e6beff', '#9a6324', '#fffac8', 18 | '#800000', '#aaffc3', '#808000', '#ffd8b1', '#000075', 19 | '#808080' 20 | ) 21 | #' distinguish colors for making figures 22 | #' @author Kai Guo 23 | #' @export 24 | distcolor<-c("#A6761D","#D95F02","#66A61E","#1B9E77","#E7298A","#7570B3","#E6AB02", 25 | "#A6CEE3", "#1F78B4", "#B2DF8A", "#33A02C", "#FB9A99", "#E31A1C", 26 | "#A6761D","#D95F02","#66A61E","#1B9E77","#E7298A","#7570B3","#E6AB02",'#e6194b', '#3cb44b', '#4363d8', 27 | '#f58231', '#911eb4', '#46f0f0', '#f032e6', '#bcf60c', 28 | '#fabebe', '#008080', '#e6beff', '#9a6324', '#fffac8', 29 | '#800000', '#aaffc3', '#808000', '#ffd8b1', '#000075', 30 | '#808080', '#ffffff', '#000000') 31 | #' do anova test and return results as data.frame 32 | #' @importFrom rstatix anova_test 33 | #' @importFrom tidyr gather 34 | #' @importFrom magrittr %>% 35 | #' @importFrom dplyr group_by 36 | #' @param x data.frame with sample id as the column name, genes or otu as rownames 37 | #' @param group group factor used for comparison 38 | #' @param ... parameters to anova_test 39 | #' @examples 40 | #' { 41 | #' data("ToothGrowth") 42 | #' do_aov(ToothGrowth,group="supp") 43 | #' } 44 | #' @export 45 | #' @author Kai Guo 46 | do_aov<-function(x,group,...){ 47 | d<-x[,setdiff(colnames(x),group)] 48 | d$group<-x[,group] 49 | d<-d%>%gather(type,val,-group) 50 | res<-d%>%group_by(type)%>%anova_test(val~group,...) 51 | return(res) 52 | } 53 | 54 | #' do t.test 55 | #' @importFrom rstatix t_test 56 | #' @importFrom tidyr gather 57 | #' @importFrom magrittr %>% 58 | #' @importFrom dplyr group_by 59 | #' @param x data.frame with sample id as the column name, genes or otu as rownames 60 | #' @param group group factor used for comparison 61 | #' @param ref reference group 62 | #' @param ... parameters to t_test 63 | #' @examples 64 | #' { 65 | #' data("mtcars") 66 | #' do_ttest(mtcars,group="vs") 67 | #' do_ttest(mtcars,group="cyl",ref="4") 68 | #' } 69 | #' @export 70 | #' @author Kai Guo 71 | do_ttest<-function(x,group,ref=NULL,...){ 72 | d<-x[,setdiff(colnames(x),group)] 73 | d$group<-x[,group] 74 | d<-d%>%gather(type,val,-group) 75 | res<-d%>%group_by(type)%>%t_test(val~group,ref.group = ref,...) 76 | res$p.adj<-p.adjust(res$p,method="BH") 77 | return(res) 78 | } 79 | 80 | #' do wilcox test 81 | #' @importFrom rstatix wilcox_test 82 | #' @importFrom tidyr gather 83 | #' @importFrom magrittr %>% 84 | #' @importFrom dplyr group_by 85 | #' @param x data.frame with sample id as the column name, genes or otu as rownames 86 | #' @param group group factor used for comparison 87 | #' @param ref reference group 88 | #' @param ... parameters to wilcox_test 89 | #' @examples 90 | #' { 91 | #' data("mtcars") 92 | #' do_wilcox(mtcars,group="vs") 93 | #' do_wilcox(mtcars,group="cyl",ref="4") 94 | #' } 95 | #' @export 96 | #' @author Kai Guo 97 | do_wilcox<-function(x,group,ref=NULL,...){ 98 | d<-x[,setdiff(colnames(x),group)] 99 | d$group<-x[,group] 100 | d<-d%>%gather(type,val,-group) 101 | res<-d%>%group_by(type)%>%wilcox_test(val~group,ref.group = ref,...) 102 | res$p.adj<-p.adjust(res$p,method="BH") 103 | return(res) 104 | } 105 | #' 106 | gm_mean = function(x, na.rm=TRUE){ 107 | exp(sum(log(x[x > 0]), na.rm=na.rm) / length(x)) 108 | } 109 | 110 | #' replace p value with star 111 | #' @param x a (non-empty) numeric data values 112 | .getstar<-function(x){ 113 | if(x>=0.05){ 114 | return("ns") 115 | }else if(x>=0.01 & x<0.05){ 116 | return("*") 117 | }else if(x<0.01){ 118 | return("**") 119 | }else{ 120 | return("***") 121 | } 122 | } 123 | #' check file format 124 | #' @param file filename 125 | .checkfile <- function(file){ 126 | ex <- strsplit(basename(file), split="\\.")[[1]] 127 | return(ex[-1]) 128 | } 129 | 130 | #' LEfse function 131 | #' @param df a dataframe with groups and bacteria abundance 132 | .lda.fun<-function(df){ 133 | # modified from https://github.com/xia-lab/MicrobiomeAnalystR/blob/ 134 | # 0a8d81afeb3b637122c97c2d17146a44fa978c4f/R/general_anal.R 135 | ldares <- MASS::lda(group~seqs,df,tol = 1.0e-10); 136 | ldamean <- as.data.frame(t(ldares$means)); 137 | class_no <- length(unique(df$group)); 138 | ldamean$max <- apply(ldamean[,1:class_no],1,max); 139 | ldamean$min <- apply(ldamean[,1:class_no],1,min); 140 | ldamean$LDAscore <- signif(log10(1+abs(ldamean$max-ldamean$min)/2),digits=3); 141 | resTable <- ldamean; 142 | resTable$direction <- colnames(resTable)[which(resTable[,1:class_no]==resTable$max)] 143 | return(resTable) 144 | } 145 | 146 | #' contruction of plylogenetic tree (extreme slow) 147 | #' @importFrom phangorn phyDat dist.ml NJ pml optim.pml pml.control 148 | #' @importFrom stats update 149 | #' @param seqs DNA sequences 150 | #' @author Kai Guo 151 | #' @return tree object 152 | #' @export 153 | buildTree<-function(seqs){ 154 | alignment <- DECIPHER::AlignSeqs(Biostrings::DNAStringSet(seqs), anchor=NA,verbose=T) 155 | phangAlign <- phyDat(as(alignment, "matrix"), type="DNA") 156 | dm <- dist.ml(phangAlign) 157 | treeNJ <- NJ(dm) # Note, tip order != sequence order 158 | fit = pml(treeNJ, data=phangAlign) 159 | fitGTR <- update(fit, k=4, inv=0.2) 160 | fitGTR <- optim.pml(fitGTR, model="GTR", optInv=TRUE, optGamma=TRUE, 161 | rearrangement = "stochastic", control = pml.control(trace = 0)) 162 | return(fitGTR) 163 | } 164 | #' extract otu table 165 | #' @param physeq (Required). An integer matrix, otu_table-class, or phyloseq-class. 166 | #' @param ... parameters for the otu_table function in phyloseq package 167 | #' @export 168 | otu_table<-function(physeq,...){ 169 | phyloseq::otu_table(physeq,...) 170 | } 171 | #' extract taxonomy table 172 | #' @param physeq An object among the set of classes defined by the phyloseq package that contain taxonomyTable. 173 | #' @param ... parameters for the tax_table function in phyloseq package 174 | #' @export 175 | tax_table<-function(physeq,...){ 176 | phyloseq::tax_table(physeq,...) 177 | } 178 | #' extract sample information 179 | #' @param physeq (Required). A data.frame-class, or a phyloseq-class object. 180 | #' @param ... parameters for the sample_data function in phyloseq package 181 | #' @export 182 | sample_data<-function(physeq,...){ 183 | phyloseq::sample_data(physeq,...) 184 | } 185 | 186 | #' Retrieve phylogenetic tree (phylo-class) from object. 187 | #' @param physeq (Required). An instance of phyloseq-class that contains a phylogenetic tree. 188 | #' If physeq is a phylogenetic tree (a component data class), then it is returned as-is. 189 | #' @param ... parameters for the phy_tree function in phyloseq package 190 | #' @export 191 | phy_tree<-function(physeq,...){ 192 | phyloseq::phy_tree(physeq,...) 193 | } 194 | 195 | #' Subset the phyloseq based on sample 196 | #' @param physeq A sample_data-class, or a phyloseq-class object with a sample_data. 197 | #' If the sample_data slot is missing in physeq, then physeq will be returned as-is, 198 | #' and a warning will be printed to screen. 199 | #' @param ... parameters for the subset_samples function in phyloseq package 200 | #' @export 201 | subset_samples<-function(physeq,...){ 202 | phyloseq::subset_samples(physeq,...) 203 | } 204 | 205 | #' Subset species by taxonomic expression 206 | #' @param physeq A sample_data-class, or a phyloseq-class object with a sample_data. 207 | #' If the sample_data slot is missing in physeq, then physeq will be returned as-is, 208 | #' and a warning will be printed to screen. 209 | #' @param ... parameters for the subset_taxa function in phyloseq package 210 | #' @export 211 | subset_taxa<-function(physeq,...){ 212 | phyloseq::subset_taxa(physeq,...) 213 | } 214 | 215 | #' Melt phyloseq data object into large data.frame 216 | #' @param physeq A sample_data-class, or a phyloseq-class object with a sample_data. 217 | #' If the sample_data slot is missing in physeq, then physeq will be returned as-is, 218 | #' and a warning will be printed to screen. 219 | #' @param ... parameters for the subset_samples function in phyloseq package 220 | #' @export 221 | psmelt<-function(physeq,...){ 222 | phyloseq::psmelt(physeq,...) 223 | } 224 | 225 | 226 | 227 | -------------------------------------------------------------------------------- /R/plot.R: -------------------------------------------------------------------------------- 1 | #' plot beta diversity 2 | #' 3 | #' @importFrom ggplot2 ggplot aes_string 4 | #' @importFrom ggplot2 geom_point 5 | #' @importFrom ggplot2 scale_color_manual 6 | #' @importFrom ggplot2 xlab ylab stat_ellipse 7 | #' @importFrom ggplot2 theme_light 8 | #' @importFrom phyloseq taxa_are_rows 9 | #' @param physeq A \code{phyloseq} object containing merged information of abundance, 10 | #' taxonomic assignment, sample data including the measured variables and categorical information 11 | #' of the samples, and / or phylogenetic tree if available. 12 | #' @param group (Required). Character string specifying name of a categorical variable that is preferred for grouping the information. 13 | #' information. 14 | #' @param shape shape(Optional) Character string specifying shape of a categorical variable 15 | #' @param method A character string specifying ordination method. All methods available to the \code{ordinate} function 16 | #' of \code{phyloseq} are acceptable here as well. 17 | #' @param distance A string character specifying dissimilarity index to be used in calculating pairwise distances (Default index is "bray".). 18 | #' "unifrac","wunifrac","manhattan", "euclidean", "canberra", "bray", "kulczynski", "jaccard", "gower", "altGower", 19 | #' "morisita", "horn", "mountford", "raup" , "binomial", "chao", "cao" or "mahalanobis". 20 | #' @param color user defined color for group 21 | #' @param size the point size 22 | #' @param ellipse draw ellipse or not 23 | #' @examples 24 | #' { 25 | #' data("Physeq") 26 | #' phy<-normalize(physeq) 27 | #' plotbeta(phy,group="SampleType") 28 | #' } 29 | #' @return ggplot2 object 30 | #' @author Kai Guo 31 | #' @export 32 | plotbeta<-function(physeq,group,shape=NULL,distance="bray",method="PCoA",color=NULL,size=3,ellipse=FALSE){ 33 | if(!taxa_are_rows(physeq)){ 34 | physeq <- t(physeq) 35 | } 36 | beta<-betadiv(physeq,distance = distance,method=method) 37 | df <- as.data.frame(beta$beta) 38 | PCs <- beta$PCs 39 | tab <- as(sample_data(physeq),"data.frame") 40 | df <- cbind(df[,1:4],tab[rownames(df),]) 41 | df$group<-tab[,group] 42 | if(is.null(color)){ 43 | color<-distcolor[1:length(unique(df$group))] 44 | } 45 | if(!is.null(shape)){ 46 | df$shape<-tab[,shape] 47 | p <- ggplot(df,aes_string("Axis.1","Axis.2",color="group",shape="shape")) 48 | }else{ 49 | p <- ggplot(df,aes_string("Axis.1","Axis.2",color="group")) 50 | } 51 | p<-p+geom_point(size=size)+scale_color_manual(values=color) 52 | p <- p+theme_light(base_size=15)+xlab(paste0("Axis1 (",round(PCs[1]*100,2),"%)"))+ylab(paste0("Axis2 (",round(PCs[2]*100,2),"%)")) 53 | if(isTRUE(ellipse)){ 54 | p <- p + stat_ellipse() 55 | } 56 | p 57 | } 58 | 59 | #' plot alpha diversity 60 | #' @importFrom rstatix t_test 61 | #' @importFrom rstatix wilcox_test 62 | #' @importFrom ggpubr ggboxplot 63 | #' @importFrom ggpubr ggviolin 64 | #' @importFrom ggpubr ggdotplot 65 | #' @importFrom ggpubr stat_pvalue_manual 66 | #' @importFrom ggpubr facet 67 | #' @importFrom ggplot2 xlab ylab scale_color_manual theme 68 | #' @importFrom dplyr summarise group_by 69 | #' @importFrom tidyr gather spread 70 | #' @param physeq A \code{phyloseq} object containing merged information of abundance, 71 | #' taxonomic assignment, sample data including the measured variables and categorical information 72 | #' of the samples, and / or phylogenetic tree if available. 73 | #' @param group group (Required). A character string specifying the name of a categorical variable containing grouping information. 74 | #' @param method A list of character strings specifying \code{method} to be used to calculate for alpha diversity 75 | #' in the data. Available methods are: "Observed","Chao1","ACE","Richness", "Fisher", "Simpson", "Shannon", "Evenness","InvSimpson". 76 | #' @param color A vector of character use specifying the color 77 | #' @param geom different geom to display("boxplot","violin","dotplot") 78 | #' @param pvalue pvalue threshold for significant dispersion results 79 | #' @param sig.only display the significant comparsion only(TRUE/ FALSE) 80 | #' @param padj adjust p value threshold for significant dispersion results 81 | #' @param wilcox use wilcoxon test or not 82 | #' @param show.number to show the pvalue instead of significant symbol(TRUE/FALSE) 83 | #' @examples 84 | #' { 85 | #' data("Physeq") 86 | #' plotalpha(physeq,group="SampleType") 87 | #' } 88 | #' @return Returns a ggplot object. This can further be manipulated as preferred by user. 89 | #' @author Kai Guo 90 | #' @export 91 | plotalpha<-function(physeq,group,method=c("Observed","Simpson", "Shannon"),color=NULL,geom="boxplot", 92 | pvalue=0.05,padj=NULL,sig.only=TRUE, wilcox=FALSE,show.number=FALSE){ 93 | if (!taxa_are_rows(physeq)) { 94 | physeq <- t(physeq) 95 | } 96 | rich<-richness(physeq,method = method) 97 | name<-levels(factor(colnames(rich))) 98 | tab<-as(sample_data(physeq),"data.frame") 99 | rich$group<-tab[rownames(rich),group] 100 | if(isTRUE(wilcox)){ 101 | res<-do_wilcox(rich,"group") 102 | }else{ 103 | res<-do_ttest(rich,"group") 104 | } 105 | if(sum(res$p%gather(type,val,-group)%>%group_by(type,group)%>%summarise(ma=max(val))%>%spread(group,ma) 116 | pos <- apply(res, 1, function(x)max(vals[vals$type==x[1],x[3:4]])) 117 | mpos <- apply(res, 1, function(x)min(vals[vals$type==x[1],x[3:4]])) 118 | if(geom=="boxplot"){ 119 | p<-rich%>%gather(type,val,-group)%>%ggboxplot(x="group",y="val",color="group") 120 | }else if(geom=="violin"){ 121 | p<-rich%>%gather(type,val,-group)%>%ggviolin(x="group",y="val",color="group") 122 | }else if(geom=="dotplot"){ 123 | p<-rich%>%gather(type,val,-group)%>%ggdotplot(x="group",y="val",color="group") 124 | }else{ 125 | stop("Please specify one type of boxplot,violin,dotplot") 126 | } 127 | if(!isTRUE(show.number)){ 128 | res$p.signif<-sapply(res$p,function(x).getstar(x)) 129 | res$p.adj.signif<-sapply(res$p.adj,function(x).getstar(x)) 130 | }else{ 131 | res$p.signif<-res$p 132 | res$p.adj.signif<-res$p.adj 133 | } 134 | if(is.null(color)){ 135 | color<-distcolor[1:length(unique(rich$group))] 136 | } 137 | p<-facet(p,facet.by = "type",scales = "free_y",ncol = length(method)) 138 | if(!is.null(padj)){ 139 | p<-p+stat_pvalue_manual(res,label = "p.adj.signif",y.position = pos+2*mpos/nrow(res)) 140 | }else{ 141 | p<-p+stat_pvalue_manual(res,label = "p.signif",y.position = pos+mpos/nrow(res)) 142 | } 143 | p<-p+xlab("")+ylab("")+ 144 | theme(legend.position = "none",axis.text.x=element_text(angle=90,vjust=0.5, hjust=1))+ 145 | scale_color_manual(values=color) 146 | p 147 | } 148 | 149 | 150 | #' plot bar for relative abundance for bacteria 151 | #' @importFrom phyloseq psmelt 152 | #' @importFrom ggplot2 ggplot 153 | #' @importFrom ggplot2 geom_bar 154 | #' @importFrom ggplot2 scale_fill_manual 155 | #' @importFrom ggplot2 theme 156 | #' @importFrom ggplot2 element_text 157 | #' @importFrom ggplot2 aes_string 158 | #' @importFrom ggplot2 element_blank scale_y_continuous 159 | #' @importFrom dplyr group_by_at 160 | #' @importFrom dplyr vars pull 161 | #' @importFrom dplyr one_of 162 | #' @importFrom dplyr summarise 163 | #' @importFrom dplyr mutate 164 | #' @importFrom dplyr select 165 | #' @importFrom rlang `!!` 166 | #' @importFrom utils head 167 | #' @param physeq A \code{phyloseq} object containing merged information of abundance, 168 | #' taxonomic assignment, sample data including the measured variables and categorical information 169 | #' of the samples, and / or phylogenetic tree if available. 170 | #' @param level the level to plot 171 | #' @param color A vector of character use specifying the color 172 | #' @param group group (Optional). A character string specifying the name of a categorical variable containing grouping information. 173 | #' @param top the number of most abundance bacteria to display 174 | #' @param return return the data with the relative abundance 175 | #' @param fontsize.x the size of x axis label 176 | #' @param fontsize.y the size of y axis label 177 | #' @examples 178 | #' \donttest{ 179 | #' data("Physeq") 180 | #' phy<-normalize(physeq) 181 | #' plotbar(phy,level="Phylum") 182 | #' } 183 | #' @return Returns a ggplot object. This can further be manipulated as preferred by user. 184 | #' @author Kai Guo 185 | #' @export 186 | plotbar<-function(physeq,level="Phylum",color=NULL,group=NULL,top=5,return=FALSE,fontsize.x = 5, fontsize.y = 12){ 187 | pm <- psmelt(physeq) 188 | if(is.null(color)){ 189 | len<-length(unique(pm[,level])) 190 | color<-distcolor[1:len] 191 | } 192 | if(is.null(group)){ 193 | group_var<-c("Sample",level) 194 | }else{ 195 | group_var<-c(group,level) 196 | } 197 | d<-pm%>%group_by_at(vars(one_of(group_var)))%>%summarise(su=sum(Abundance)) 198 | d <- as.data.frame(d) 199 | d[,level][is.na(d[,level])]<-"NA" 200 | dx <- pm%>%group_by_at(vars(one_of(level)))%>%summarise(su=sum(Abundance)) 201 | dx <- dx[order(dx$su,decreasing = T),] 202 | sel <- dx%>%head(top)%>%select(!!level)%>%pull(1) 203 | d <- d[d[,level]%in%sel,] 204 | if(is.null(group)){ 205 | p<-ggplot(d,aes_string("Sample","su",fill=level)) 206 | }else{ 207 | p<-ggplot(d,aes_string(group,"su",fill=level)) 208 | } 209 | p<-p+geom_bar(stat = "identity",position = "fill")+scale_fill_manual(values=color)+ 210 | theme_light()+ 211 | scale_y_continuous(expand = c(0, 0.001)) + 212 | theme(axis.text.x=element_text(angle=90,size=fontsize.x, vjust=0.5, hjust=1), 213 | axis.text.y=element_text(size=fontsize.y), 214 | panel.background = element_blank(),axis.ticks.x = element_blank())+ 215 | xlab("")+ylab("") 216 | if(isTRUE(return)){ 217 | return(pm[,c("OTU","Abundance",group_var)]) 218 | }else{ 219 | return(p) 220 | } 221 | } 222 | 223 | #' @title plot differential results 224 | #' @importFrom ggplot2 ggplot theme geom_point element_text xlab 225 | #' @importFrom ggplot2 aes_string scale_color_manual theme_light coord_flip 226 | #' @param res differential test results from diff_test 227 | #' @param level the level to plot 228 | #' @param color A vector of character use specifying the color 229 | #' @param pvalue pvalue threshold for significant results 230 | #' @param padj adjust p value threshold for significant results 231 | #' @param log2FC log2 Fold Change threshold 232 | #' @param size size for the point 233 | #' @param fontsize.x the size of x axis label 234 | #' @param fontsize.y the size of y axis label 235 | #' @param horiz horizontal or not (TRUE/FALSE) 236 | #' @examples 237 | #' \donttest{ 238 | #' data("Physeq") 239 | #' res <- difftest(physeq,group="group") 240 | #' plotdiff(res,level="Genus",padj=0.001) 241 | #' } 242 | #' @return ggplot object 243 | #' @author Kai Guo 244 | #' @export 245 | plotdiff<-function(res,level="Genus",color=NULL,pvalue=0.05,padj=NULL,log2FC=0,size=3,fontsize.x=5,fontsize.y=10,horiz=TRUE){ 246 | if(!is.null(padj)){ 247 | pval<-padj 248 | sigtab <- subset(res,padjlog2FC) 249 | }else{ 250 | pval<-pvalue 251 | sigtab <- subset(res,pvaluelog2FC) 252 | } 253 | x <- tapply(sigtab$log2FoldChange, sigtab$Phylum, function(x) max(x)) 254 | x <- sort(x, TRUE) 255 | sigtab$Phylum <- factor(as.character(sigtab$Phylum), levels=names(x)) 256 | if(is.null(color)){ 257 | len<-length(unique(sigtab$Phylum)) 258 | color<-distcolor[1:len] 259 | } 260 | # Genus order 261 | sigtab$name<-paste0(sigtab[,level],"(",rownames(sigtab),")") 262 | x <- tapply(sigtab$log2FoldChange, sigtab$name, function(x) max(x)) 263 | x <- sort(x, TRUE) 264 | sigtab$name <- factor(as.character(sigtab$name), levels=names(x)) 265 | p <- ggplot(sigtab, aes_string(x="name", y="log2FoldChange", color="Phylum"))+ 266 | geom_point(size=3) +theme_light()+xlab(level)+ 267 | theme(axis.text.x = element_text(angle = -90, hjust = 0, vjust=0.5,size=fontsize.x), 268 | axis.text.y = element_text(size=fontsize.y))+ 269 | scale_color_manual(values=color) 270 | if(isTRUE(horiz)){ 271 | p<-p+coord_flip()+theme(axis.text.x=element_text(angle=0,size=fontsize.x)) 272 | } 273 | p 274 | } 275 | 276 | #' plot LEfSe results from ldamarker function 277 | #' @importFrom ggplot2 ggplot geom_bar coord_flip theme_light element_text 278 | #' @importFrom ggplot2 scale_fill_manual xlab 279 | #' @importFrom ggplot2 aes 280 | #' @importFrom dplyr mutate 281 | #' @importFrom magrittr %>% 282 | #' @importFrom stats reorder 283 | #' @param x LEfse results from ldamarker 284 | #' @param group a vector include two character to show the group comparsion 285 | #' @param lda LDA threshold for significant biomarker 286 | #' @param pvalue pvalue threshold for significant results 287 | #' @param padj adjust p value threshold for significant results 288 | #' @param color A vector of character use specifying the color 289 | #' @param fontsize.x the size of x axis label 290 | #' @param fontsize.y the size of y axis label 291 | #' @examples 292 | #' \donttest{ 293 | #' data("Physeq") 294 | #' res <- ldamarker(physeq,group="group") 295 | #' plotLDA(res,group=c("A","B"),lda=5,pvalue=0.05) 296 | #' } 297 | #' @return ggplot2 object 298 | #' @author Kai Guo 299 | #' @export 300 | plotLDA<-function(x,group,lda=2,pvalue=0.05,padj=NULL,color=NULL,fontsize.x=4,fontsize.y=5){ 301 | x <- subset(x,LDAscore>lda) 302 | if(!is.null(padj)){ 303 | x <- subset(x,p.adj%mutate(LDA=ifelse(direction==group[1],LDAscore,-LDAscore)) 309 | p<-ggplot(x,aes(x=reorder(tax,LDA),y=LDA,fill=direction))+ 310 | geom_bar(stat="identity",color="white")+coord_flip()+ 311 | theme_light()+theme(axis.text.x = element_text(size=fontsize.x), 312 | axis.text.y = element_text(size=fontsize.y)) 313 | if(is.null(color)){ 314 | color <- distcolor[c(2:3)] 315 | } 316 | p<-p+scale_fill_manual(values=color)+xlab("") 317 | p 318 | } 319 | 320 | #' 321 | #' plot the biomarker from the biomarker function with randomForest 322 | #' @importFrom ggpubr ggdotchart 323 | #' @importFrom ggplot2 xlab ylab 324 | #' @param x biomarker results from randomForest 325 | #' @param level the bacteria level to display 326 | #' @param top the number of important biomarker to draw 327 | #' @param rotate TRUE/FALSE 328 | #' @param dot.size size for the dot 329 | #' @param label.size label size 330 | #' @param label.color label color 331 | #' @return ggplot2 object 332 | #' @examples 333 | #' \donttest{ 334 | #' data("Physeq") 335 | #' res <- biomarker(physeq,group="group") 336 | #' plotmarker(res,level="Genus") 337 | #' } 338 | #' @export 339 | #' @author Kai Guo 340 | plotmarker<-function(x,level="Genus",top=30,rotate=FALSE,dot.size=8,label.color="black",label.size=6){ 341 | x <- x[1:top,] 342 | x <- x[order(x$Value),] 343 | x$label<-paste0(x[,level],"(",x$OTU,")") 344 | p<-ggdotchart(x,x="label",y="Value",add="segments",color=I("#00AFBB"),rotate=rotate,dot.size=dot.size,sorting="descending", 345 | add.params = list(color = "#00AFBB", size = 1.5), 346 | label=round(x$Value,2),font.label = list(color = label.color, size = label.size,vjust=0.2)) 347 | if(isTRUE(rotate)){ 348 | p<-p+xlab(level)+ylab("Mean Decrease Accuracy") 349 | }else{ 350 | p<-p+xlab(level)+ylab("Mean Decrease Accuracy") 351 | } 352 | p 353 | } 354 | 355 | #' plot the quality for the fastq file 356 | #' @param file (Required). character. File path(s) to fastq or fastq.gz file(s). 357 | #' @param n (Optional). Default 500,000. The number of records to sample from the fastq file. 358 | #' @param aggregate (Optional). Default FALSE. If TRUE, compute an aggregate quality profile for all fastq files provided. 359 | #' @examples 360 | #' \donttest{ 361 | #' plotquality(system.file("extdata", "sam1F.fastq.gz", package="dada2")) 362 | #' } 363 | #' @export 364 | #' @return figure 365 | plotquality<-function(file,n = 5e+05, aggregate = FALSE){ 366 | dada2::plotQualityProfile(file,n=n,aggregate = aggregate) 367 | } 368 | -------------------------------------------------------------------------------- /R/zzz.R: -------------------------------------------------------------------------------- 1 | .onLoad <- function(libname, pkgname) { 2 | old <- options() 3 | options(stringsAsFactors = FALSE) 4 | on.exit(options(old)) 5 | } 6 | if(getRversion() >= "2.15.1") { 7 | utils::globalVariables(c(".","Abundance", "Group","LDA","LDAscore", "OTU", 8 | "Phylum","Sample","direction", 9 | "log2FoldChange","ma","p.adj", 10 | "p.value", "tax","type", "val")) 11 | } 12 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # microbial 2 | CRAN version 3 | [![DOI](https://zenodo.org/badge/298122205.svg)](https://zenodo.org/badge/latestdoi/298122205) 4 | ![](http://cranlogs.r-pkg.org/badges/grand-total/microbial?color=green) 5 | [![Project Status:](http://www.repostatus.org/badges/latest/active.svg)](http://www.repostatus.org/#active) 6 | [![](https://img.shields.io/badge/devel%20version-0.0.22-green.svg)](https://github.com/guokai8/microbial)![Code Size:](https://img.shields.io/github/languages/code-size/guokai8/microbial) 7 | [![](https://cranlogs.r-pkg.org/badges/microbial)](https://cran.r-project.org/package=microbial) 8 | 9 | 10 | An R package for microbial community analysis with dada2 and phyloseq 11 | 12 | _microbial_ is a R package for microbial community analysis with dada2 and phyloseq 13 | This package is developed to enhance the available statistical analysis procedures in R by providing simple functions to analysis and visualize the 16S rRNA data.Here we present a tutorial with minimum working examples to demonstrate usage and dependencies. 14 | 15 | ## 1. Data format/ requirement 16 | To use the package user can start with the raw fastq files with sample information ready or user can start with a phyloseq object (phloseq-class) comprising taxa abundance information, taxonomy assignment, sample data which is a combination of the measured environmental variables and any categorical variables present in the sample. 17 | 18 | If the phylogenetic tree is available, it can also be part of it, but it has nothing to do with most of the functions implemented here so far. We chose to use this format because as the analysis and visualization proceed, we have many options to process the data.User can go to the https://github.com/joey711/phyloseq to check the detail format of phyloseq object. 19 | 20 | ## 2 Example data 21 | The physeq data were the Global patterns of 16S rRNA diversity at a depth of millions of sequences per sample (2011). The data was published in PNAS in early 2011. This work compared the microbial communities from 25 environmental samples and three known “mock communities” – a total of 9 sample types – at a depth averaging 3.1 million reads per sample. Authors were able to reproduce diversity patterns seen in many other published studies, while also invesitigating technical issues/bias by applying the same techniques to simulated microbial communities of known composition. We simple modified the data with add one more group factor to display some functions implemented in the package. 22 | 23 | ## 3. Software Usage 24 | ### 3.1 Installation 25 | Install the package with its dependencies and load it for usage in R. 26 | ``` {r install, eval = FALSE} 27 | install.packages("microbial") 28 | #or install the develop version 29 | library(devtools) # Load the devtools package 30 | install_github("guokai8/microbial") # Install the package 31 | ``` 32 | ``` 33 | # You can use processSeq function to do analysis start from fastq files 34 | ?processSeq 35 | # You may need to first download the reference database 36 | preRef(ref_db="silva") 37 | # to check the quality of you reads 38 | ?plotquality 39 | ``` 40 | 41 | ### 3.2 Data normalisation 42 | Microbial community data is mainly OTU abundance (counts) with different design data.It is usually necessary that data is transformed by a suitable normalisation method. 43 | We provided different methods including; “relative”, “TMM”,variance stabilisation "vst" and "log2" for normalisation of taxa abundance. The function takes a phyloseq object physeq and returns a similar object whose otu-table component is normalised by a selected method as shown in the following examples. 44 | ``` {r quick, message=FALSE} 45 | library(microbial) 46 | data("Physeq") 47 | #default normalize method is relative 48 | phy <- normalize(physeq, method = "relative") 49 | ``` 50 | ### 3.3 relative abundance among all samples or groups 51 | We first use relative normalised bacteria abundance to obtain the proportion of per sample. Then we generate the figure to show the proportion among all samples based on "Phylum" level. The _group_ parameter is provided to show the proportion based on group level. 52 | ```{r plotbar, message=FALSE} 53 | plotbar(phy,level="Phylum") 54 | #or among two group 55 | plotbar(phy,level="Phylum", group="group") 56 | 57 | ``` 58 | 59 | ### 3.4 Alpha diversity with wilcoxon test or t-test 60 | The _richness_ calculate the alpha diversity of provided community data using selected indices/method(s). Alpha diversity refers to the diversity within a particular area or ecosystem, and is usually expressed by the number of species. The _plotalpha_ function performs pair-wise wilcoxon test or t-test of diversity measures between groups and outputs a plot for each of the selected methods(indices) annotated with significance labels. 61 | 62 | The _method_ in the _richness_ function include: "Observed", "Chao1", "ACE", "Richness", "Fisher", "Simpson", "Shannon", "Evenness" and "InvSimpson". The _group_ paramater in the _plotalpha_ function is a categorical variable for which the grouping should be based on during the analysi, the _group_ should be one of the _sample_data_ column. _pvalue_ specifies the p-value threshold for significance in wilcoxon, default is set to 0.05. User can also choose to use the _padj_ paramter instead of _pvalue_. The _plotalpha_ function return a _ggplot2_ object which will easy to modified by user. 63 | ```{r alpha, message = FALSE} 64 | plotalpha(physeq, group = "group") 65 | ``` 66 | 67 | ### 3.5 Beta diversity 68 | Beta diversity is a comparison of of diversity between groups, usually measured as the amount of species change between the groups. In the example provided below, we first normalize the taxa abundance to relative abundance to obtain the proportion of most abundant taxa per sample. 69 | The arguments in the _plotbeta_ function include: _physeq_ which a required phyloseq object, the _distance_ which is a dissimilarity distance measure with otions of “bray” (default), "unifrac","wunifrac","manhattan", "euclidean", "canberra", "bray", "kulczynski", "jaccard" and other distance methods, the _group_ is a character string specifying a variable whose levels are the groups in the data, the _method_ paramater is a character string specifying ordination method. All methods available to the ordinate function of phyloseq are acceptable here as well. The _plotbeta_ function will return _ggplot2_ object. 70 | ```{r plotbeta, message = FALSE} 71 | plotbeta(phy, group="SampleType") 72 | ``` 73 | 74 | We also provide _betatest_ function by doing permutation analysis of variance (PERMANOVA) and return corresponding r-squared and p-values, beta dispersion between all posible pairwise combinations of levels in the grouping variable is calculated and results return as a table. 75 | ```{r betatest, message = FALSE} 76 | beta <-betatest(phy,group="SampleType") 77 | ``` 78 | 79 | ### 3.6 Differentail expression 80 | Here we provide _difftest_ function to find features that are up or down regulated in the compared groups using DESeq2 package. The _plotdiff_ function produce figure of the top most features annotated with corresponding adjusted p-values and abundance distribution. The _difftest_ require a _phyloseq_ object containing merged information of abundance, taxonomic assignment, sample data including the measured variables and categorical information of the samples. Raw count values are preferred for this function. The _group_ paramater is a character string specifying the name of a categorical variable containing grouping information. The _pvalue_ and _log2FC_ are thresholds for p values and log2 fold change. Adjusted p value cutoff is also supported by specify the _padj_ paramater. 81 | ```{r difftest, message = FALSE} 82 | res <- difftest(physeq,group="group") 83 | ``` 84 | 85 | The _plotdiff_ function require the differential test results from diff_test. And the _level_ parameter provide which level to show: "Genus", "Species" or other level. Other paramaters can be found in the man page of _plotdiff_. 86 | 87 | 88 | ```{r plotdiff, message = FALSE} 89 | plotdiff(res,level="Genus",padj=0.001,log2FC = 7,fontsize.y = 3) 90 | 91 | ``` 92 | 93 | ### 3.7 Biomarker selection 94 | In addition we implement classification using random forest classifier and LEfSe method to find most import features among the groups. 95 | Random forests or random decision forests are an ensemble learning method for classification. 96 | And the random forest classifier is used to determine the importance of differentially expressed bacteria/taxa to the microbial community. Typically, we will use the Mean Descrease in Accuracy to measure the importance for each bacteria/taxa. The _biomarker_ function do the random forest classification and return the sigificant table include the importance values. Raw count values are preferred for this function, and user can specify the normalize method with the _method_ parameter. 97 | ```{r biomarker,message=FALSE} 98 | res <- biomarker(physeq,group="group") 99 | ``` 100 | 101 | The _plotmarker_ function will generate the figures based on the _biomarker_ result. User can specify level to show with the _level_ parameter and also the _top_ parameter will choose the number of top most importance bacteria and taxa to draw. 102 | ```{r plotmarker,message = FALSE} 103 | plotmarker(res,level="Genus") 104 | ``` 105 | We also provide _ldamarker_ function to do the LEfSe analysis which base on the kruskal-wallis test and the LDA analysis. The parameters include _physeq_ (A phyloseq object) and _group_ (a character string specifying the name of a categorical variable containing grouping information. ). Raw count values are preferred for this function, and user can also specify the normalize method with the _method_ parameter. 106 | ```{r lda, message=FALSE} 107 | res <- ldamarker(physeq,group="group") 108 | ``` 109 | The _plotLDA_ function take the results from _ldamarker_ and _group_ factor which was used for the LEfSe analysis to generate figure with the significant bacteria marker. 110 | 111 | ```{r plotlda, message = FALSE} 112 | plotLDA(res,group=c("A","B"),lda=5,pvalue=0.05) 113 | ``` 114 | 115 | ## 4. Dependencies 116 | This packages depends on a number of other packages which include: phyloseq, vegan, DESeq2, ggplot2,randomForest. The package is still under development. New functions will be provided soon. 117 | 118 | ## 5. Contact information 119 | For any questions please contact guokai8@gmail.com or submit the issues to https://github.com/guokai8/microbial/issues 120 | -------------------------------------------------------------------------------- /data/Physeq.rda: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/guokai8/microbial/b587bd20c6467a365512af56fbc9d36e29ae7966/data/Physeq.rda -------------------------------------------------------------------------------- /man/betadiv.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/Functions.R 3 | \name{betadiv} 4 | \alias{betadiv} 5 | \title{calcaute beta diversity} 6 | \usage{ 7 | betadiv(physeq, distance = "bray", method = "PCoA") 8 | } 9 | \arguments{ 10 | \item{physeq}{A \code{phyloseq} object containing merged information of abundance, 11 | taxonomic assignment, sample data including the measured variables and categorical information 12 | of the samples, and / or phylogenetic tree if available.} 13 | 14 | \item{distance}{A string character specifying dissimilarity index to be used in calculating pairwise distances (Default index is "bray".). 15 | "unifrac","wunifrac","manhattan", "euclidean", "canberra", "bray", "kulczynski", "jaccard", "gower", "altGower", 16 | "morisita", "horn", "mountford", "raup" , "binomial", "chao", "cao" or "mahalanobis".} 17 | 18 | \item{method}{A character string specifying ordination method. All methods available to the \code{ordinate} function 19 | of \code{phyloseq} are acceptable here as well.} 20 | } 21 | \value{ 22 | list with beta diversity data.frame and PCs 23 | } 24 | \description{ 25 | calcaute beta diversity 26 | } 27 | \examples{ 28 | { 29 | data("Physeq") 30 | phy<-normalize(physeq) 31 | res <- betadiv(phy) 32 | } 33 | } 34 | \author{ 35 | Kai Guo 36 | } 37 | -------------------------------------------------------------------------------- /man/betatest.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/Functions.R 3 | \name{betatest} 4 | \alias{betatest} 5 | \title{PERMANOVA test for phyloseq} 6 | \usage{ 7 | betatest(physeq, group, distance = "bray") 8 | } 9 | \arguments{ 10 | \item{physeq}{A \code{phyloseq} object containing merged information of abundance, 11 | taxonomic assignment, sample data including the measured variables and categorical information 12 | of the samples, and / or phylogenetic tree if available.} 13 | 14 | \item{group}{(Required). Character string specifying name of a categorical variable that is preferred for grouping the information. 15 | information.} 16 | 17 | \item{distance}{A string character specifying dissimilarity index to be used in calculating pairwise distances (Default index is "bray".). 18 | "unifrac","wunifrac","manhattan", "euclidean", "canberra", "bray", "kulczynski", "jaccard", "gower", "altGower", 19 | "morisita", "horn", "mountford", "raup" , "binomial", "chao", "cao" or "mahalanobis".} 20 | } 21 | \value{ 22 | PERMANOVA test result 23 | } 24 | \description{ 25 | PERMANOVA test for phyloseq 26 | } 27 | \examples{ 28 | { 29 | data("Physeq") 30 | phy<-normalize(physeq) 31 | beta <-betatest(phy,group="SampleType") 32 | } 33 | } 34 | \author{ 35 | Kai Guo 36 | } 37 | -------------------------------------------------------------------------------- /man/biomarker.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/Functions.R 3 | \name{biomarker} 4 | \alias{biomarker} 5 | \title{Identify biomarker by using randomForest method} 6 | \usage{ 7 | biomarker( 8 | physeq, 9 | group, 10 | ntree = 500, 11 | pvalue = 0.05, 12 | normalize = TRUE, 13 | method = "relative" 14 | ) 15 | } 16 | \arguments{ 17 | \item{physeq}{A \code{phyloseq} object containing merged information of abundance, 18 | taxonomic assignment, sample data including the measured variables and categorical information 19 | of the samples, and / or phylogenetic tree if available.} 20 | 21 | \item{group}{group. A character string specifying the name of a categorical variable containing grouping information.} 22 | 23 | \item{ntree}{Number of trees to grow. This should not be set to too small a number, 24 | to ensure that every input row gets predicted at least a few times.} 25 | 26 | \item{pvalue}{pvalue threshold for significant results from kruskal.test} 27 | 28 | \item{normalize}{to normalize the data before analysis(TRUE/FALSE)} 29 | 30 | \item{method}{A list of character strings specifying \code{method} to be used to normalize the phyloseq object 31 | Available methods are: "relative","TMM","vst","log2".} 32 | } 33 | \value{ 34 | data frame with significant biomarker 35 | } 36 | \description{ 37 | Identify biomarker by using randomForest method 38 | } 39 | \examples{ 40 | \donttest{ 41 | data("Physeq") 42 | res <- biomarker(physeq,group="group") 43 | } 44 | } 45 | \author{ 46 | Kai Guo 47 | } 48 | -------------------------------------------------------------------------------- /man/buildTree.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/misc.R 3 | \name{buildTree} 4 | \alias{buildTree} 5 | \title{contruction of plylogenetic tree (extreme slow)} 6 | \usage{ 7 | buildTree(seqs) 8 | } 9 | \arguments{ 10 | \item{seqs}{DNA sequences} 11 | } 12 | \value{ 13 | tree object 14 | } 15 | \description{ 16 | contruction of plylogenetic tree (extreme slow) 17 | } 18 | \author{ 19 | Kai Guo 20 | } 21 | -------------------------------------------------------------------------------- /man/data-Physeq.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/data.R 3 | \docType{data} 4 | \name{data-Physeq} 5 | \alias{data-Physeq} 6 | \alias{Physeq} 7 | \title{The physeq data was modified from the (Data) Global patterns of 16S rRNA diversity at a depth of millions of sequences per sample (2011)} 8 | \description{ 9 | Published in PNAS in early 2011. This work compared the microbial 10 | communities from 25 environmental samples and three known ``mock communities'' 11 | -- a total of 9 sample types -- at a depth averaging 3.1 million reads per sample. 12 | Authors were able to reproduce diversity patterns seen in many other 13 | published studies, while also invesitigating technical issues/bias by 14 | applying the same techniques to simulated microbial communities of known 15 | } 16 | \examples{ 17 | data(Physeq) 18 | plot_richness(physeq, x="SampleType", measures=c("Observed", "Shannon")) 19 | } 20 | \references{ 21 | Caporaso, J. G., et al. (2011). 22 | Global patterns of 16S rRNA diversity at a depth of millions of sequences per sample. 23 | PNAS, 108, 4516-4522. 24 | PMCID: PMC3063599 25 | } 26 | \keyword{data} 27 | -------------------------------------------------------------------------------- /man/data-physeq.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/data.R 3 | \docType{data} 4 | \name{data-physeq} 5 | \alias{data-physeq} 6 | \alias{physeq} 7 | \title{The physeq data was modified from the (Data) Global patterns of 16S rRNA diversity at a depth of millions of sequences per sample (2011)} 8 | \description{ 9 | Published in PNAS in early 2011. This work compared the microbial 10 | communities from 25 environmental samples and three known ``mock communities'' 11 | -- a total of 9 sample types -- at a depth averaging 3.1 million reads per sample. 12 | Authors were able to reproduce diversity patterns seen in many other 13 | published studies, while also invesitigating technical issues/bias by 14 | applying the same techniques to simulated microbial communities of known 15 | } 16 | \examples{ 17 | data(Physeq) 18 | } 19 | \references{ 20 | Caporaso, J. G., et al. (2011). 21 | Global patterns of 16S rRNA diversity at a depth of millions of sequences per sample. 22 | PNAS, 108, 4516-4522. 23 | PMCID: PMC3063599 24 | } 25 | \keyword{data} 26 | -------------------------------------------------------------------------------- /man/difftest.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/Functions.R 3 | \name{difftest} 4 | \alias{difftest} 5 | \title{Calculate differential bacteria with DESeq2} 6 | \usage{ 7 | difftest( 8 | physeq, 9 | group, 10 | ref = NULL, 11 | pvalue = 0.05, 12 | padj = NULL, 13 | log2FC = 0, 14 | gm_mean = TRUE, 15 | fitType = "local", 16 | quiet = FALSE 17 | ) 18 | } 19 | \arguments{ 20 | \item{physeq}{A \code{phyloseq} object containing merged information of abundance, 21 | taxonomic assignment, sample data including the measured variables and categorical information 22 | of the samples, and / or phylogenetic tree if available.} 23 | 24 | \item{group}{group (DESeq2). A character string specifying the name of a categorical variable containing grouping information.} 25 | 26 | \item{ref}{reference group} 27 | 28 | \item{pvalue}{pvalue threshold for significant results} 29 | 30 | \item{padj}{adjust p value threshold for significant results} 31 | 32 | \item{log2FC}{log2 Fold Change threshold} 33 | 34 | \item{gm_mean}{TRUE/FALSE calculate geometric means prior to estimate size factors} 35 | 36 | \item{fitType}{either "parametric", "local", or "mean" for the type of fitting of dispersions to the mean intensity.} 37 | 38 | \item{quiet}{whether to print messages at each step} 39 | } 40 | \value{ 41 | datafame with differential test with DESeq2 42 | } 43 | \description{ 44 | Calculate differential bacteria with DESeq2 45 | } 46 | \examples{ 47 | \donttest{ 48 | data("Physeq") 49 | res <- difftest(physeq,group="group") 50 | } 51 | } 52 | \author{ 53 | Kai Guo 54 | } 55 | -------------------------------------------------------------------------------- /man/distcolor.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/misc.R 3 | \docType{data} 4 | \name{distcolor} 5 | \alias{distcolor} 6 | \title{distinguish colors for making figures} 7 | \format{ 8 | An object of class \code{character} of length 41. 9 | } 10 | \usage{ 11 | distcolor 12 | } 13 | \description{ 14 | distinguish colors for making figures 15 | } 16 | \author{ 17 | Kai Guo 18 | } 19 | \keyword{datasets} 20 | -------------------------------------------------------------------------------- /man/do_aov.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/misc.R 3 | \name{do_aov} 4 | \alias{do_aov} 5 | \title{do anova test and return results as data.frame} 6 | \usage{ 7 | do_aov(x, group, ...) 8 | } 9 | \arguments{ 10 | \item{x}{data.frame with sample id as the column name, genes or otu as rownames} 11 | 12 | \item{group}{group factor used for comparison} 13 | 14 | \item{...}{parameters to anova_test} 15 | } 16 | \description{ 17 | do anova test and return results as data.frame 18 | } 19 | \examples{ 20 | { 21 | data("ToothGrowth") 22 | do_aov(ToothGrowth,group="supp") 23 | } 24 | } 25 | \author{ 26 | Kai Guo 27 | } 28 | -------------------------------------------------------------------------------- /man/do_ttest.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/misc.R 3 | \name{do_ttest} 4 | \alias{do_ttest} 5 | \title{do t.test} 6 | \usage{ 7 | do_ttest(x, group, ref = NULL, ...) 8 | } 9 | \arguments{ 10 | \item{x}{data.frame with sample id as the column name, genes or otu as rownames} 11 | 12 | \item{group}{group factor used for comparison} 13 | 14 | \item{ref}{reference group} 15 | 16 | \item{...}{parameters to t_test} 17 | } 18 | \description{ 19 | do t.test 20 | } 21 | \examples{ 22 | { 23 | data("mtcars") 24 | do_ttest(mtcars,group="vs") 25 | do_ttest(mtcars,group="cyl",ref="4") 26 | } 27 | } 28 | \author{ 29 | Kai Guo 30 | } 31 | -------------------------------------------------------------------------------- /man/do_wilcox.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/misc.R 3 | \name{do_wilcox} 4 | \alias{do_wilcox} 5 | \title{do wilcox test} 6 | \usage{ 7 | do_wilcox(x, group, ref = NULL, ...) 8 | } 9 | \arguments{ 10 | \item{x}{data.frame with sample id as the column name, genes or otu as rownames} 11 | 12 | \item{group}{group factor used for comparison} 13 | 14 | \item{ref}{reference group} 15 | 16 | \item{...}{parameters to wilcox_test} 17 | } 18 | \description{ 19 | do wilcox test 20 | } 21 | \examples{ 22 | { 23 | data("mtcars") 24 | do_wilcox(mtcars,group="vs") 25 | do_wilcox(mtcars,group="cyl",ref="4") 26 | } 27 | } 28 | \author{ 29 | Kai Guo 30 | } 31 | -------------------------------------------------------------------------------- /man/dot-checkfile.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/misc.R 3 | \name{.checkfile} 4 | \alias{.checkfile} 5 | \title{check file format} 6 | \usage{ 7 | .checkfile(file) 8 | } 9 | \arguments{ 10 | \item{file}{filename} 11 | } 12 | \description{ 13 | check file format 14 | } 15 | -------------------------------------------------------------------------------- /man/dot-getstar.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/misc.R 3 | \name{.getstar} 4 | \alias{.getstar} 5 | \title{replace p value with star} 6 | \usage{ 7 | .getstar(x) 8 | } 9 | \arguments{ 10 | \item{x}{a (non-empty) numeric data values} 11 | } 12 | \description{ 13 | replace p value with star 14 | } 15 | -------------------------------------------------------------------------------- /man/dot-lda.fun.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/misc.R 3 | \name{.lda.fun} 4 | \alias{.lda.fun} 5 | \title{LEfse function} 6 | \usage{ 7 | .lda.fun(df) 8 | } 9 | \arguments{ 10 | \item{df}{a dataframe with groups and bacteria abundance} 11 | } 12 | \description{ 13 | LEfse function 14 | } 15 | -------------------------------------------------------------------------------- /man/glmr.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/glmr.R 3 | \name{glmr} 4 | \alias{glmr} 5 | \title{Do the generalized linear model regression} 6 | \usage{ 7 | glmr( 8 | physeq, 9 | group, 10 | factors = NULL, 11 | ref = NULL, 12 | family = binomial(link = "logit") 13 | ) 14 | } 15 | \arguments{ 16 | \item{physeq}{phyloseq object} 17 | 18 | \item{group}{the group factor to regression} 19 | 20 | \item{factors}{a vector to indicate adjuested factors} 21 | 22 | \item{ref}{the reference group} 23 | 24 | \item{family}{binomial() or gaussian()} 25 | } 26 | \description{ 27 | Do the generalized linear model regression 28 | } 29 | \examples{ 30 | \donttest{ 31 | data("Physeq") 32 | phy<-normalize(physeq) 33 | fit <-glmr(phy,group="SampleType") 34 | } 35 | } 36 | \author{ 37 | Kai Guo 38 | } 39 | -------------------------------------------------------------------------------- /man/ldamarker.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/Functions.R 3 | \name{ldamarker} 4 | \alias{ldamarker} 5 | \title{Identify biomarker by using LEfSe method} 6 | \usage{ 7 | ldamarker(physeq, group, pvalue = 0.05, normalize = TRUE, method = "relative") 8 | } 9 | \arguments{ 10 | \item{physeq}{A \code{phyloseq} object containing merged information of abundance, 11 | taxonomic assignment, sample data including the measured variables and categorical information 12 | of the samples, and / or phylogenetic tree if available.} 13 | 14 | \item{group}{group. A character string specifying the name of a categorical variable containing grouping information.} 15 | 16 | \item{pvalue}{pvalue threshold for significant results from kruskal.test} 17 | 18 | \item{normalize}{to normalize the data before analysis(TRUE/FALSE)} 19 | 20 | \item{method}{A list of character strings specifying \code{method} to be used to normalize the phyloseq object 21 | Available methods are: "relative","TMM","vst","log2".} 22 | } 23 | \description{ 24 | Identify biomarker by using LEfSe method 25 | } 26 | \examples{ 27 | \donttest{ 28 | data("Physeq") 29 | res <- ldamarker(physeq,group="group") 30 | } 31 | 32 | } 33 | \author{ 34 | Kai Guo 35 | } 36 | -------------------------------------------------------------------------------- /man/lightcolor.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/misc.R 3 | \docType{data} 4 | \name{lightcolor} 5 | \alias{lightcolor} 6 | \title{light colors for making figures} 7 | \format{ 8 | An object of class \code{character} of length 56. 9 | } 10 | \usage{ 11 | lightcolor 12 | } 13 | \description{ 14 | light colors for making figures 15 | } 16 | \author{ 17 | Kai Guo 18 | } 19 | \keyword{datasets} 20 | -------------------------------------------------------------------------------- /man/normalize.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/Functions.R 3 | \name{normalize} 4 | \alias{normalize} 5 | \title{Normalize the phyloseq object with different methods} 6 | \usage{ 7 | normalize(physeq, group, method = "relative", table = FALSE) 8 | } 9 | \arguments{ 10 | \item{physeq}{A \code{phyloseq} object containing merged information of abundance, 11 | taxonomic assignment, sample data including the measured variables and categorical information 12 | of the samples, and / or phylogenetic tree if available.} 13 | 14 | \item{group}{group (DESeq2). A character string specifying the name of a categorical variable containing grouping information.} 15 | 16 | \item{method}{A list of character strings specifying \code{method} to be used to normalize the phyloseq object 17 | Available methods are: "relative","TMM","vst","log2".} 18 | 19 | \item{table}{return a data.frame or not} 20 | } 21 | \value{ 22 | phyloseq object with normalized data 23 | } 24 | \description{ 25 | Normalize the phyloseq object with different methods 26 | } 27 | \examples{ 28 | { 29 | data("Physeq") 30 | phy<-normalize(physeq) 31 | } 32 | } 33 | \author{ 34 | Kai Guo 35 | } 36 | -------------------------------------------------------------------------------- /man/otu_table.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/misc.R 3 | \name{otu_table} 4 | \alias{otu_table} 5 | \title{extract otu table} 6 | \usage{ 7 | otu_table(physeq, ...) 8 | } 9 | \arguments{ 10 | \item{physeq}{(Required). An integer matrix, otu_table-class, or phyloseq-class.} 11 | 12 | \item{...}{parameters for the otu_table function in phyloseq package} 13 | } 14 | \description{ 15 | extract otu table 16 | } 17 | -------------------------------------------------------------------------------- /man/phy_tree.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/misc.R 3 | \name{phy_tree} 4 | \alias{phy_tree} 5 | \title{Retrieve phylogenetic tree (phylo-class) from object.} 6 | \usage{ 7 | phy_tree(physeq, ...) 8 | } 9 | \arguments{ 10 | \item{physeq}{(Required). An instance of phyloseq-class that contains a phylogenetic tree. 11 | If physeq is a phylogenetic tree (a component data class), then it is returned as-is.} 12 | 13 | \item{...}{parameters for the phy_tree function in phyloseq package} 14 | } 15 | \description{ 16 | Retrieve phylogenetic tree (phylo-class) from object. 17 | } 18 | -------------------------------------------------------------------------------- /man/plotLDA.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/plot.R 3 | \name{plotLDA} 4 | \alias{plotLDA} 5 | \title{plot LEfSe results from ldamarker function} 6 | \usage{ 7 | plotLDA( 8 | x, 9 | group, 10 | lda = 2, 11 | pvalue = 0.05, 12 | padj = NULL, 13 | color = NULL, 14 | fontsize.x = 4, 15 | fontsize.y = 5 16 | ) 17 | } 18 | \arguments{ 19 | \item{x}{LEfse results from ldamarker} 20 | 21 | \item{group}{a vector include two character to show the group comparsion} 22 | 23 | \item{lda}{LDA threshold for significant biomarker} 24 | 25 | \item{pvalue}{pvalue threshold for significant results} 26 | 27 | \item{padj}{adjust p value threshold for significant results} 28 | 29 | \item{color}{A vector of character use specifying the color} 30 | 31 | \item{fontsize.x}{the size of x axis label} 32 | 33 | \item{fontsize.y}{the size of y axis label} 34 | } 35 | \value{ 36 | ggplot2 object 37 | } 38 | \description{ 39 | plot LEfSe results from ldamarker function 40 | } 41 | \examples{ 42 | \donttest{ 43 | data("Physeq") 44 | res <- ldamarker(physeq,group="group") 45 | plotLDA(res,group=c("A","B"),lda=5,pvalue=0.05) 46 | } 47 | } 48 | \author{ 49 | Kai Guo 50 | } 51 | -------------------------------------------------------------------------------- /man/plotalpha.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/plot.R 3 | \name{plotalpha} 4 | \alias{plotalpha} 5 | \title{plot alpha diversity} 6 | \usage{ 7 | plotalpha( 8 | physeq, 9 | group, 10 | method = c("Observed", "Simpson", "Shannon"), 11 | color = NULL, 12 | geom = "boxplot", 13 | pvalue = 0.05, 14 | padj = NULL, 15 | sig.only = TRUE, 16 | wilcox = FALSE, 17 | show.number = FALSE 18 | ) 19 | } 20 | \arguments{ 21 | \item{physeq}{A \code{phyloseq} object containing merged information of abundance, 22 | taxonomic assignment, sample data including the measured variables and categorical information 23 | of the samples, and / or phylogenetic tree if available.} 24 | 25 | \item{group}{group (Required). A character string specifying the name of a categorical variable containing grouping information.} 26 | 27 | \item{method}{A list of character strings specifying \code{method} to be used to calculate for alpha diversity 28 | in the data. Available methods are: "Observed","Chao1","ACE","Richness", "Fisher", "Simpson", "Shannon", "Evenness","InvSimpson".} 29 | 30 | \item{color}{A vector of character use specifying the color} 31 | 32 | \item{geom}{different geom to display("boxplot","violin","dotplot")} 33 | 34 | \item{pvalue}{pvalue threshold for significant dispersion results} 35 | 36 | \item{padj}{adjust p value threshold for significant dispersion results} 37 | 38 | \item{sig.only}{display the significant comparsion only(TRUE/ FALSE)} 39 | 40 | \item{wilcox}{use wilcoxon test or not} 41 | 42 | \item{show.number}{to show the pvalue instead of significant symbol(TRUE/FALSE)} 43 | } 44 | \value{ 45 | Returns a ggplot object. This can further be manipulated as preferred by user. 46 | } 47 | \description{ 48 | plot alpha diversity 49 | } 50 | \examples{ 51 | { 52 | data("Physeq") 53 | plotalpha(physeq,group="SampleType") 54 | } 55 | } 56 | \author{ 57 | Kai Guo 58 | } 59 | -------------------------------------------------------------------------------- /man/plotbar.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/plot.R 3 | \name{plotbar} 4 | \alias{plotbar} 5 | \title{plot bar for relative abundance for bacteria} 6 | \usage{ 7 | plotbar( 8 | physeq, 9 | level = "Phylum", 10 | color = NULL, 11 | group = NULL, 12 | top = 5, 13 | return = FALSE, 14 | fontsize.x = 5, 15 | fontsize.y = 12 16 | ) 17 | } 18 | \arguments{ 19 | \item{physeq}{A \code{phyloseq} object containing merged information of abundance, 20 | taxonomic assignment, sample data including the measured variables and categorical information 21 | of the samples, and / or phylogenetic tree if available.} 22 | 23 | \item{level}{the level to plot} 24 | 25 | \item{color}{A vector of character use specifying the color} 26 | 27 | \item{group}{group (Optional). A character string specifying the name of a categorical variable containing grouping information.} 28 | 29 | \item{top}{the number of most abundance bacteria to display} 30 | 31 | \item{return}{return the data with the relative abundance} 32 | 33 | \item{fontsize.x}{the size of x axis label} 34 | 35 | \item{fontsize.y}{the size of y axis label} 36 | } 37 | \value{ 38 | Returns a ggplot object. This can further be manipulated as preferred by user. 39 | } 40 | \description{ 41 | plot bar for relative abundance for bacteria 42 | } 43 | \examples{ 44 | \donttest{ 45 | data("Physeq") 46 | phy<-normalize(physeq) 47 | plotbar(phy,level="Phylum") 48 | } 49 | } 50 | \author{ 51 | Kai Guo 52 | } 53 | -------------------------------------------------------------------------------- /man/plotbeta.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/plot.R 3 | \name{plotbeta} 4 | \alias{plotbeta} 5 | \title{plot beta diversity} 6 | \usage{ 7 | plotbeta( 8 | physeq, 9 | group, 10 | shape = NULL, 11 | distance = "bray", 12 | method = "PCoA", 13 | color = NULL, 14 | size = 3, 15 | ellipse = FALSE 16 | ) 17 | } 18 | \arguments{ 19 | \item{physeq}{A \code{phyloseq} object containing merged information of abundance, 20 | taxonomic assignment, sample data including the measured variables and categorical information 21 | of the samples, and / or phylogenetic tree if available.} 22 | 23 | \item{group}{(Required). Character string specifying name of a categorical variable that is preferred for grouping the information. 24 | information.} 25 | 26 | \item{shape}{shape(Optional) Character string specifying shape of a categorical variable} 27 | 28 | \item{distance}{A string character specifying dissimilarity index to be used in calculating pairwise distances (Default index is "bray".). 29 | "unifrac","wunifrac","manhattan", "euclidean", "canberra", "bray", "kulczynski", "jaccard", "gower", "altGower", 30 | "morisita", "horn", "mountford", "raup" , "binomial", "chao", "cao" or "mahalanobis".} 31 | 32 | \item{method}{A character string specifying ordination method. All methods available to the \code{ordinate} function 33 | of \code{phyloseq} are acceptable here as well.} 34 | 35 | \item{color}{user defined color for group} 36 | 37 | \item{size}{the point size} 38 | 39 | \item{ellipse}{draw ellipse or not} 40 | } 41 | \value{ 42 | ggplot2 object 43 | } 44 | \description{ 45 | plot beta diversity 46 | } 47 | \examples{ 48 | { 49 | data("Physeq") 50 | phy<-normalize(physeq) 51 | plotbeta(phy,group="SampleType") 52 | } 53 | } 54 | \author{ 55 | Kai Guo 56 | } 57 | -------------------------------------------------------------------------------- /man/plotdiff.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/plot.R 3 | \name{plotdiff} 4 | \alias{plotdiff} 5 | \title{plot differential results} 6 | \usage{ 7 | plotdiff( 8 | res, 9 | level = "Genus", 10 | color = NULL, 11 | pvalue = 0.05, 12 | padj = NULL, 13 | log2FC = 0, 14 | size = 3, 15 | fontsize.x = 5, 16 | fontsize.y = 10, 17 | horiz = TRUE 18 | ) 19 | } 20 | \arguments{ 21 | \item{res}{differential test results from diff_test} 22 | 23 | \item{level}{the level to plot} 24 | 25 | \item{color}{A vector of character use specifying the color} 26 | 27 | \item{pvalue}{pvalue threshold for significant results} 28 | 29 | \item{padj}{adjust p value threshold for significant results} 30 | 31 | \item{log2FC}{log2 Fold Change threshold} 32 | 33 | \item{size}{size for the point} 34 | 35 | \item{fontsize.x}{the size of x axis label} 36 | 37 | \item{fontsize.y}{the size of y axis label} 38 | 39 | \item{horiz}{horizontal or not (TRUE/FALSE)} 40 | } 41 | \value{ 42 | ggplot object 43 | } 44 | \description{ 45 | plot differential results 46 | } 47 | \examples{ 48 | \donttest{ 49 | data("Physeq") 50 | res <- difftest(physeq,group="group") 51 | plotdiff(res,level="Genus",padj=0.001) 52 | } 53 | } 54 | \author{ 55 | Kai Guo 56 | } 57 | -------------------------------------------------------------------------------- /man/plotmarker.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/plot.R 3 | \name{plotmarker} 4 | \alias{plotmarker} 5 | \title{plot the biomarker from the biomarker function with randomForest} 6 | \usage{ 7 | plotmarker( 8 | x, 9 | level = "Genus", 10 | top = 30, 11 | rotate = FALSE, 12 | dot.size = 8, 13 | label.color = "black", 14 | label.size = 6 15 | ) 16 | } 17 | \arguments{ 18 | \item{x}{biomarker results from randomForest} 19 | 20 | \item{level}{the bacteria level to display} 21 | 22 | \item{top}{the number of important biomarker to draw} 23 | 24 | \item{rotate}{TRUE/FALSE} 25 | 26 | \item{dot.size}{size for the dot} 27 | 28 | \item{label.color}{label color} 29 | 30 | \item{label.size}{label size} 31 | } 32 | \value{ 33 | ggplot2 object 34 | } 35 | \description{ 36 | plot the biomarker from the biomarker function with randomForest 37 | } 38 | \examples{ 39 | \donttest{ 40 | data("Physeq") 41 | res <- biomarker(physeq,group="group") 42 | plotmarker(res,level="Genus") 43 | } 44 | } 45 | \author{ 46 | Kai Guo 47 | } 48 | -------------------------------------------------------------------------------- /man/plotquality.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/plot.R 3 | \name{plotquality} 4 | \alias{plotquality} 5 | \title{plot the quality for the fastq file} 6 | \usage{ 7 | plotquality(file, n = 5e+05, aggregate = FALSE) 8 | } 9 | \arguments{ 10 | \item{file}{(Required). character. File path(s) to fastq or fastq.gz file(s).} 11 | 12 | \item{n}{(Optional). Default 500,000. The number of records to sample from the fastq file.} 13 | 14 | \item{aggregate}{(Optional). Default FALSE. If TRUE, compute an aggregate quality profile for all fastq files provided.} 15 | } 16 | \value{ 17 | figure 18 | } 19 | \description{ 20 | plot the quality for the fastq file 21 | } 22 | \examples{ 23 | \donttest{ 24 | plotquality(system.file("extdata", "sam1F.fastq.gz", package="dada2")) 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /man/preRef.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/Functions.R 3 | \name{preRef} 4 | \alias{preRef} 5 | \title{Download the reference database} 6 | \usage{ 7 | preRef(ref_db, path = ".") 8 | } 9 | \arguments{ 10 | \item{ref_db}{the reference database} 11 | 12 | \item{path}{path for the database} 13 | } 14 | \value{ 15 | the path of the database 16 | } 17 | \description{ 18 | Download the reference database 19 | } 20 | \examples{ 21 | \donttest{ 22 | preRef(ref_db="silva",path=tempdir()) 23 | } 24 | } 25 | \author{ 26 | Kai Guo 27 | } 28 | -------------------------------------------------------------------------------- /man/prefilter.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/Functions.R 3 | \name{prefilter} 4 | \alias{prefilter} 5 | \title{filter the phyloseq} 6 | \usage{ 7 | prefilter(physeq, min = 10, perc = 0.05) 8 | } 9 | \arguments{ 10 | \item{physeq}{A \code{phyloseq} object containing merged information of abundance, 11 | taxonomic assignment, sample data including the measured variables and categorical information 12 | of the samples, and / or phylogenetic tree if available.} 13 | 14 | \item{min}{Numeric, the threshold for mininal Phylum shown in samples} 15 | 16 | \item{perc}{Numeric, input the percentage of samples for which to filter low counts.} 17 | } 18 | \value{ 19 | filter phyloseq object 20 | } 21 | \description{ 22 | filter the phyloseq 23 | } 24 | \examples{ 25 | \donttest{ 26 | data("Physeq") 27 | physeqs<-prefilter(physeq) 28 | } 29 | } 30 | \author{ 31 | Kai Guo 32 | } 33 | -------------------------------------------------------------------------------- /man/processSeq.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/dada2.R 3 | \name{processSeq} 4 | \alias{processSeq} 5 | \title{Perform dada2 analysis} 6 | \usage{ 7 | processSeq( 8 | path = ".", 9 | truncLen = c(0, 0), 10 | trimLeft = 0, 11 | trimRight = 0, 12 | minLen = 20, 13 | maxLen = Inf, 14 | sample_info = NULL, 15 | train_data = "silva_nr99_v138_train_set.fa.gz", 16 | train_species = "silva_species_assignment_v138.fa.gz", 17 | outpath = NULL, 18 | saveobj = FALSE, 19 | buildtree = FALSE, 20 | verbose = TRUE 21 | ) 22 | } 23 | \arguments{ 24 | \item{path}{working dir for the input reads} 25 | 26 | \item{truncLen}{(Optional). Default 0 (no truncation). Truncate reads after truncLen bases. Reads shorter than this are discarded.} 27 | 28 | \item{trimLeft}{(Optional). The number of nucleotides to remove from the start of each read.} 29 | 30 | \item{trimRight}{(Optional). Default 0. The number of nucleotides to remove from the end of each read. 31 | If both truncLen and trimRight are provided, truncation will be performed after trimRight is enforced.} 32 | 33 | \item{minLen}{(Optional). Default 20. Remove reads with length less than minLen. minLen is enforced after trimming and truncation.} 34 | 35 | \item{maxLen}{Optional). Default Inf (no maximum). Remove reads with length greater than maxLen. maxLen is enforced before trimming and truncation.} 36 | 37 | \item{sample_info}{(Optional).sample information for the sequence} 38 | 39 | \item{train_data}{(Required).training database} 40 | 41 | \item{train_species}{(Required). species database} 42 | 43 | \item{outpath}{(Optional).the path for the filtered reads and th out table} 44 | 45 | \item{saveobj}{(Optional).Default FALSE. save the phyloseq object output.} 46 | 47 | \item{buildtree}{build phylogenetic tree or not(default: FALSE)} 48 | 49 | \item{verbose}{(Optional). Default TRUE. Print verbose text output.} 50 | } 51 | \value{ 52 | list include count table, summary table, taxonomy information and phyloseq object 53 | } 54 | \description{ 55 | Perform dada2 analysis 56 | } 57 | \author{ 58 | Kai Guo 59 | } 60 | -------------------------------------------------------------------------------- /man/psmelt.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/misc.R 3 | \name{psmelt} 4 | \alias{psmelt} 5 | \title{Melt phyloseq data object into large data.frame} 6 | \usage{ 7 | psmelt(physeq, ...) 8 | } 9 | \arguments{ 10 | \item{physeq}{A sample_data-class, or a phyloseq-class object with a sample_data. 11 | If the sample_data slot is missing in physeq, then physeq will be returned as-is, 12 | and a warning will be printed to screen.} 13 | 14 | \item{...}{parameters for the subset_samples function in phyloseq package} 15 | } 16 | \description{ 17 | Melt phyloseq data object into large data.frame 18 | } 19 | -------------------------------------------------------------------------------- /man/richness.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/Functions.R 3 | \name{richness} 4 | \alias{richness} 5 | \title{calculat the richness for the phyloseq object} 6 | \usage{ 7 | richness(physeq, method = c("Observed", "Simpson", "Shannon")) 8 | } 9 | \arguments{ 10 | \item{physeq}{A \code{phyloseq} object containing merged information of abundance, 11 | taxonomic assignment, sample data including the measured variables and categorical information 12 | of the samples, and / or phylogenetic tree if available.} 13 | 14 | \item{method}{A list of character strings specifying \code{method} to be used to calculate for alpha diversity 15 | in the data. Available methods are: "Observed","Chao1","ACE","Richness", "Fisher", "Simpson", "Shannon", "Evenness","InvSimpson".} 16 | } 17 | \value{ 18 | data.frame of alpha diversity 19 | } 20 | \description{ 21 | calculat the richness for the phyloseq object 22 | } 23 | \examples{ 24 | { 25 | data("Physeq") 26 | rich <-richness(physeq,method=c("Simpson", "Shannon")) 27 | } 28 | } 29 | \author{ 30 | Kai Guo 31 | } 32 | -------------------------------------------------------------------------------- /man/sample_data.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/misc.R 3 | \name{sample_data} 4 | \alias{sample_data} 5 | \title{extract sample information} 6 | \usage{ 7 | sample_data(physeq, ...) 8 | } 9 | \arguments{ 10 | \item{physeq}{(Required). A data.frame-class, or a phyloseq-class object.} 11 | 12 | \item{...}{parameters for the sample_data function in phyloseq package} 13 | } 14 | \description{ 15 | extract sample information 16 | } 17 | -------------------------------------------------------------------------------- /man/subset_samples.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/misc.R 3 | \name{subset_samples} 4 | \alias{subset_samples} 5 | \title{Subset the phyloseq based on sample} 6 | \usage{ 7 | subset_samples(physeq, ...) 8 | } 9 | \arguments{ 10 | \item{physeq}{A sample_data-class, or a phyloseq-class object with a sample_data. 11 | If the sample_data slot is missing in physeq, then physeq will be returned as-is, 12 | and a warning will be printed to screen.} 13 | 14 | \item{...}{parameters for the subset_samples function in phyloseq package} 15 | } 16 | \description{ 17 | Subset the phyloseq based on sample 18 | } 19 | -------------------------------------------------------------------------------- /man/subset_taxa.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/misc.R 3 | \name{subset_taxa} 4 | \alias{subset_taxa} 5 | \title{Subset species by taxonomic expression} 6 | \usage{ 7 | subset_taxa(physeq, ...) 8 | } 9 | \arguments{ 10 | \item{physeq}{A sample_data-class, or a phyloseq-class object with a sample_data. 11 | If the sample_data slot is missing in physeq, then physeq will be returned as-is, 12 | and a warning will be printed to screen.} 13 | 14 | \item{...}{parameters for the subset_taxa function in phyloseq package} 15 | } 16 | \description{ 17 | Subset species by taxonomic expression 18 | } 19 | -------------------------------------------------------------------------------- /man/tax_table.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/misc.R 3 | \name{tax_table} 4 | \alias{tax_table} 5 | \title{extract taxonomy table} 6 | \usage{ 7 | tax_table(physeq, ...) 8 | } 9 | \arguments{ 10 | \item{physeq}{An object among the set of classes defined by the phyloseq package that contain taxonomyTable.} 11 | 12 | \item{...}{parameters for the tax_table function in phyloseq package} 13 | } 14 | \description{ 15 | extract taxonomy table 16 | } 17 | -------------------------------------------------------------------------------- /microbial.Rproj: -------------------------------------------------------------------------------- 1 | Version: 1.0 2 | 3 | RestoreWorkspace: Default 4 | SaveWorkspace: Default 5 | AlwaysSaveHistory: Default 6 | 7 | EnableCodeIndexing: Yes 8 | UseSpacesForTab: Yes 9 | NumSpacesForTab: 4 10 | Encoding: UTF-8 11 | 12 | RnwWeave: Sweave 13 | LaTeX: pdfLaTeX 14 | 15 | AutoAppendNewline: Yes 16 | StripTrailingWhitespace: Yes 17 | 18 | BuildType: Package 19 | PackageUseDevtools: Yes 20 | PackageInstallArgs: --no-multiarch --with-keep.source 21 | -------------------------------------------------------------------------------- /tests/testthat.R: -------------------------------------------------------------------------------- 1 | library(testthat) 2 | library(microbial) 3 | test_check("microbial") 4 | -------------------------------------------------------------------------------- /tests/testthat/test-microbial.R: -------------------------------------------------------------------------------- 1 | library(microbial) 2 | expect_silent(1+1) 3 | -------------------------------------------------------------------------------- /vignettes/microbial.Rmd: -------------------------------------------------------------------------------- 1 | --- 2 | title: "The microbial package for microbial community analysis" 3 | author: 4 | - Kai Guo, University of Michigan 5 | - Pan Gao, University of North Dakota 6 | date: "`r Sys.Date()`" 7 | output: 8 | html_document: 9 | df_print: paged 10 | word_document: 11 | toc: yes 12 | toc_depth: '6' 13 | rmarkdown::html_vignette: default 14 | pdf_document: 15 | toc: yes 16 | toc_depth: 6 17 | vignette: | 18 | \usepackage[utf8]{inputenc} 19 | %\VignetteIndexEntry{microbial} 20 | %\VignetteEngine{knitr::knitr} 21 | --- 22 | _microbial_ is a R package for microbial community analysis with dada2 (https://benjjneb.github.io/dada2/) and phyloseq (https://joey711.github.io/phyloseq/). 23 | _microbial_ package is developed to enhance the available statistical analysis procedures in R by providing simple functions to analysis and visualize the 16S rRNA data.Here we present a tutorial with minimum working examples to demonstrate usage and dependencies. 24 | 25 | ## 1. Data format/ requirement 26 | To use the package user can start with the raw fastq files with sample information ready or user can start with a phyloseq object (phloseq-class) comprising taxa abundance information, taxonomy assignment, sample data which is a combination of the measured environmental variables and any categorical variables present in the sample. 27 | 28 | If the phylogenetic tree is available, it can also be part of it, but it has nothing to do with most of the functions implemented here so far. We chose to use this format because as the analysis and visualization proceed, we have many options to process the data.User can go to the https://github.com/joey711/phyloseq to check the detail format of phyloseq object. 29 | 30 | ## 2 Example data 31 | The physeq data were the Global patterns of 16S rRNA diversity at a depth of millions of sequences per sample (2011). The data was published in PNAS in early 2011. This work compared the microbial communities from 25 environmental samples and three known “mock communities” – a total of 9 sample types – at a depth averaging 3.1 million reads per sample. Authors were able to reproduce diversity patterns seen in many other published studies, while also invesitigating technical issues/bias by applying the same techniques to simulated microbial communities of known composition. We simple modified the data with add one more group factor to display some functions implemented in the package. 32 | 33 | ## 3. Software Usage 34 | ### 3.1 Installation 35 | Install the package with its dependencies and load it for usage in R. 36 | ``` {r install, eval = FALSE} 37 | library(devtools) # Load the devtools package 38 | install_github("guokai8/microbial") # Install the package 39 | ``` 40 | ### 3.2 Start from fastq files 41 | To start with the raw _fastq_ files, the users need first have the reference database ready. The _preRef_ function provides easy way to download the references. The _ref_db_ parameter is a character to choose which database to download: _silva_, _rdp_ and Greengenes. The _path_ parameter show the location to store the database. 42 | ```{r download, eval=FALSE} 43 | preRef(ref_db = "silva", path=".") 44 | ``` 45 | 46 | Then users can use the _plotquality_ function to show the quality of the reads which will help the users to specify _processSeq_ to perform the analysis with _dada2_ package. The parameters included in this function were same as the _dada2_ function. The _path_ is the working path for the input reads. The _truncLen_ is an optional parameter with the default 0 (no truncation): Truncate reads after truncLen bases. Reads shorter than this are discarded. The _trimLeft_ and _trimRight_ are the number of nucleotides to remove from the start and end of each read. 47 | ```{r processSeq, eval=FALSE} 48 | ?processSeq 49 | ``` 50 | 51 | ### 3.3 Data normalisation 52 | Microbial community data is mainly OTU abundance (counts) with different design data.It is usually necessary that data is transformed by a suitable normalisation method. 53 | We provided different methods including; “relative”, “TMM”,variance stabilisation "vst" and "log2" for normalisation of taxa abundance. The function takes a phyloseq object physeq and returns a similar object whose otu-table component is normalised by a selected method as shown in the following examples. 54 | ``` {r quick, message=FALSE} 55 | library(microbial) 56 | data("Physeq") 57 | #default normalize method is relative 58 | phy <- normalize(physeq, method = "relative") 59 | ``` 60 | ### 3.4 Relative abundance among all samples or groups 61 | We first use relative normalised bacteria abundance to obtain the proportion of per sample. Then we generate the figure to show the proportion among all samples based on "Phylum" level. The _group_ parameter is provided to show the proportion based on group level. 62 | ```{r plotbar, message=FALSE} 63 | plotbar(phy,level="Phylum") 64 | #or among two group 65 | # plotbar(phy,level="Phylum", group="group") 66 | 67 | ``` 68 | 69 | ### 3.5 Alpha diversity with wilcoxon test or t-test 70 | The _richness_ calculate the alpha diversity of provided community data using selected indices/method(s). Alpha diversity refers to the diversity within a particular area or ecosystem, and is usually expressed by the number of species. The _plotalpha_ function performs pair-wise wilcoxon test or t-test of diversity measures between groups and outputs a plot for each of the selected methods(indices) annotated with significance labels. 71 | 72 | The _method_ in the _richness_ function include: "Observed", "Chao1", "ACE", "Richness", "Fisher", "Simpson", "Shannon", "Evenness" and "InvSimpson". The _group_ paramater in the _plotalpha_ function is a categorical variable for which the grouping should be based on during the analysi, the _group_ should be one of the _sample_data_ column. _pvalue_ specifies the p-value threshold for significance in wilcoxon, default is set to 0.05. User can also choose to use the _padj_ paramter instead of _pvalue_. The _plotalpha_ function return a _ggplot2_ object which will easy to modified by user. 73 | ```{r alpha, message = FALSE} 74 | plotalpha(physeq, group = "group") 75 | ``` 76 | 77 | ### 3.6 Beta diversity 78 | Beta diversity is a comparison of of diversity between groups, usually measured as the amount of species change between the groups. In the example provided below, we first normalize the taxa abundance to relative abundance to obtain the proportion of most abundant taxa per sample. 79 | The arguments in the _plotbeta_ function include: _physeq_ which a required phyloseq object, the _distance_ which is a dissimilarity distance measure with otions of “bray” (default), "unifrac","wunifrac","manhattan", "euclidean", "canberra", "bray", "kulczynski", "jaccard" and other distance methods, the _group_ is a character string specifying a variable whose levels are the groups in the data, the _method_ paramater is a character string specifying ordination method. All methods available to the ordinate function of phyloseq are acceptable here as well. The _plotbeta_ function will return _ggplot2_ object. 80 | ```{r plotbeta, message = FALSE} 81 | plotbeta(phy, group="SampleType") 82 | ``` 83 | 84 | We also provide _betatest_ function by doing permutation analysis of variance (PERMANOVA) and return corresponding r-squared and p-values, beta dispersion between all posible pairwise combinations of levels in the grouping variable is calculated and results return as a table. 85 | ```{r betatest, message = FALSE,eval=FALSE} 86 | beta <-betatest(phy,group="SampleType") 87 | ``` 88 | 89 | ### 3.7 Differentail expression 90 | Here we provide _difftest_ function to find features that are up or down regulated in the compared groups using DESeq2 package. The _plotdiff_ function produce figure of the top most features annotated with corresponding adjusted p-values and abundance distribution. The _difftest_ require a _phyloseq_ object containing merged information of abundance, taxonomic assignment, sample data including the measured variables and categorical information of the samples. Raw count values are preferred for this function. The _group_ paramater is a character string specifying the name of a categorical variable containing grouping information. The _pvalue_ and _log2FC_ are thresholds for p values and log2 fold change. Adjusted p value cutoff is also supported by specify the _padj_ paramater. 91 | ```{r difftest, message = FALSE,eval=FALSE} 92 | res <- difftest(physeq,group="group") 93 | ``` 94 | 95 | The _plotdiff_ function require the differential test results from diff_test. And the _level_ parameter provide which level to show: "Genus", "Species" or other level. Other paramaters can be found in the man page of _plotdiff_. 96 | 97 | 98 | ```{r plotdiff, message = FALSE,eval=FALSE} 99 | plotdiff(res,level="Genus",padj=0.001,log2FC = 7,fontsize.y = 3) 100 | 101 | ``` 102 | 103 | ### 3.8 Biomarker selection 104 | In addition we implement classification using random forest classifier and LEfSe method to find most import features among the groups. 105 | Random forests or random decision forests are an ensemble learning method for classification. 106 | And the random forest classifier is used to determine the importance of differentially expressed bacteria/taxa to the microbial community. Typically, we will use the Mean Descrease in Accuracy to measure the importance for each bacteria/taxa. The _biomarker_ function do the random forest classification and return the sigificant table include the importance values. Raw count values are preferred for this function, and user can specify the normalize method with the _method_ parameter. 107 | ```{r biomarker,message=FALSE,eval=FALSE} 108 | res <- biomarker(physeq,group="group",ntree = 100) 109 | ``` 110 | 111 | The _plotmarker_ function will generate the figures based on the _biomarker_ result. User can specify level to show with the _level_ parameter and also the _top_ parameter will choose the number of top most importance bacteria and taxa to draw. 112 | ```{r plotmarker,message = FALSE,eval=FALSE} 113 | plotmarker(res,level="Genus") 114 | ``` 115 | 116 | We also provide _ldamarker_ function to do the LEfSe analysis which base on the kruskal-wallis test and the LDA analysis. The parameters include _physeq_ (A phyloseq object) and _group_ (a character string specifying the name of a categorical variable containing grouping information. ). Raw count values are preferred for this function, and user can also specify the normalize method with the _method_ parameter. 117 | ```{r lda, message=FALSE,eval=FALSE} 118 | res <- ldamarker(physeq,group="group") 119 | ``` 120 | The _plotLDA_ function take the results from _ldamarker_ and _group_ factor which was used for the LEfSe analysis to generate figure with the significant bacteria marker. 121 | 122 | ```{r plotlda, message = FALSE,eval=FALSE} 123 | plotLDA(res,group=c("A","B"),lda=5,pvalue=0.05) 124 | ``` 125 | 126 | ## 4. Dependencies 127 | This packages depends on a number of other packages which include: phyloseq, vegan, DESeq2, ggplot2,randomForest. The package is still under development. New functions will be provided soon. 128 | 129 | ## 5. Contact information 130 | For any questions please contact guokai8@gmail.com or submit the issues to https://github.com/guokai8/microbial/issues 131 | 132 | --------------------------------------------------------------------------------