-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsearch.json
More file actions
677 lines (677 loc) · 244 KB
/
Copy pathsearch.json
File metadata and controls
677 lines (677 loc) · 244 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
[
{
"objectID": "index.html",
"href": "index.html",
"title": "DAiR Workshop 2024",
"section": "",
"text": "Author: Dr. Hamed Abdollahi \n PI: Dr. Homayoun Valafar\nWelcome to our workshop on using R, a powerful and versatile environment for statistical computing and research. Our goal is to provide you with a comprehensive introduction to R, drawing from our extensive experience in both teaching and learning the language over the years.\nWhile we have endeavored to simplify the content as much as possible, this workshop is not an exhaustive guide to R—covering everything would be an impossible task. Additionally, this is not a beginner’s course in statistics, though we will employ some basic statistical concepts to demonstrate the capabilities of R.",
"crumbs": [
"Home",
"DAiR Workshop 2024"
]
},
{
"objectID": "index.html#what-is-r",
"href": "index.html#what-is-r",
"title": "DAiR Workshop 2024",
"section": "What is R",
"text": "What is R\n\nR is a comprehensive software suite designed for data manipulation, computation, and graphical visualization.\nIt is an open source versatile environment utilized for newly developing methods of interactive data analysis.\nR can be seen as an implementation of the S language. The S language also serves as the foundation for the S-Plus systems.\nThe programming languages S (1985) , which received the ACM Software Systems Award in 19981, developed by John M. Chambers(Chambers 1998).\nIn 1992, George Ross Ihaka and Robert Gentleman, from the University of Auckland, developed R based on the programming languages S and Scheme (1975).\nGeorge Ross Ihaka and Robert Gentleman published their experience as a statistical computing language in 1996(Ihaka and Gentleman 1996).\nThe inaugural “stable beta2” version, denoted as v1.0, was officially launched on February 29, 20003 .\nR features a vast library primarily written in C, C++, Fortran, and R.\nR facilitates tasks such as linear and nonlinear modeling, statistical tests, time series analysis, classification, clustering, and more.\nR has emerged as the leading statistical software in the scientific community.\nIt excels in analyzing data and producing insights for companies and institutions, empowering them to make informed business decisions.",
"crumbs": [
"Home",
"DAiR Workshop 2024"
]
},
{
"objectID": "index.html#installation-of-r-rstudio",
"href": "index.html#installation-of-r-rstudio",
"title": "DAiR Workshop 2024",
"section": "Installation of R & RStudio",
"text": "Installation of R & RStudio\n\n\n \"Note: To install additional source packages that include C or Fortran code, you will need compiler tools such as Rtools on Windows or clang/gfortran on OS X.\"\n\n\n\n\n\n \n Streamlined Installation Process for R and Rstudio \n\n\n\n \n Windows\n \n \n macOS\n \n \n Linux\n \n \n Install R in Jupyter\n \n \nR in Visual Studio Code \nClose All\n\n\n\n \n \n 1. Install R for Windows by downloading and running the .exe file from CRAN.\n Additionally, download and install the recommended version of Rtools.\n 2. Installing R on Microsoft Windows may encounter some known issues ( R for Windows FAQ).\n Step 1:\n \n Step 2:\n \n Step 3:\n \n Step 4:\n \n Step 5:\n \n Step 6:\n \n Step 7:\n \n Step 8:\n \n Step 9:\n \n Step 10:\n \n Step 11:\n \n 3. If you'd like to delve deeper into the process, feel free to explore How to Build R-devel and packages on Windows\n 4. You have the option to uninstall R directly from the Control Panel.\n 5. Please ensure to install the RStudio IDE specifically designed for Windows operating systems.\n Step 1:\n \n Step 2:\n \n Step 3:\n \n Step 4:\n \n Step 5:\n \n 6. Keep in mind that if you're operating with separate user and admin accounts, it's advisable to run the installers as an administrator.\n 7. For optimal performance, please note that RStudio Pro for Windows necessitates a 64-bit edition of Microsoft Windows 10 or a more recent version.\n 8. Leverage Git BASH for Command-Line Efficiency\n 9. Powershell provides a versatile task automation solution, comprising a command-line shell, a scripting language, and a configuration management framework. It is compatible with Windows, Linux, and macOS operating systems.\n 10. Scoop is a command-line installer for Windows that allows users to install software packages directly from the command prompt or PowerShell, streamlining the installation process.\n \n \n\n\n\n \n \n 1. Install R for macOS by downloading the installer from CRAN. Click to open the installer. Click Continue and proceed through the installer. \n Additionally, download and install the latest clang and gfortran compilers from the tools section.\n 2. In order to compile R for macOS, you will need the tools here.\n Step 1: (Details About the Downloaded Version)\n \n Step 2: (Terms and License)\n \n Step 3: (Terms and License)\n \n Step 4:(Consent to the Terms and License)\n \n Step 5: (Select Installation Location and Proceed with Installation)\n \n Step 6:\n \n Step 7:\n \n Step 8:\n \n 3. Also, please install the RStudio IDE for macOS. Follow the instructions provided by the installer for macOS.\n 4. RStudio for Mac requires macOS 10.15 (Catalina) or newer. Download the disk image (.dmg) and open it. Drag the RStudio icon to Applications then eject the disk image once complete. To uninstall, move RStudio from where it was installed to the trash.\n 5. In every version of Mac OS X, bash serves as the default shell, so there's no requirement for additional installations. To access bash, simply navigate to the Terminal, conveniently located in /Applications/Utilities.\n 6. Download Git for macOS if it's not already available.\n \n \n\n\n\n \n \n 1. Install R for Linux [Debian, fedora, Ubuntu]using your package manager or by downloading the source code from CRAN and compiling it.\n 2. Building R from source is customary on Linux and Unix systems, whereas on Mac OS X or Windows platforms, it's not the standard practice.\n 3. While constructing your own binaries might potentially boost R's performance, utilizing prebuilt binaries doesn't pose significant issues even when handling large datasets.\n 4. Also, please install the RStudio IDE for Linux. Refer to the documentation of your Linux distribution for specific instructions.\n 5. Acquire and Deploy Git for Linux and Unix\n \n \n\n\n\n \n \n 1. Make sure Jupyter Notebook is installed on your computer.2. In R or RStudio use R kernel for Jupyter Notebook\n \n \n\n\n\n \n \n 1. Install R Version 3.4.0 or Higher on Your Platform.\n 2. Install languageserver in R.\n 3. Make sure Visual Studio IDE is installed on your computer.4. Use R Extension for Visual Studio Code which provides support for the R programming language.\n5. For installation, launch VS Code Quick Open (Ctrl+P), paste [ext install REditorSupport.r], and press enter.\n\n\n\n6. For more information visit R in Visual Studio Code\n\n \n\n\nClose All\n\n\n\n\n\n\n\n\n\n\n \"Workshop Notice: We'll Be Using Ubuntu!\"\n\n\n\n\n \n \n \n \n \n \n \n \n\n\nThis workshop pertains to Ubuntu package of R, version 4.3.3 (released on February 29, 2024). Users running R on Windows or macOS may need to make minor adjustments accordingly.\nYou can check here for some of the most frequently asked questions about R.\n\n \n\n\n \n Popularity of R\n \n PYPL\n PLRank\n Stack Overflow\n RedMonk\n \n \n \n \n Link to the \"World Wide & US\" 🔗\n \n \n \n \n \n \n \n \n \n \n \n \n \n Link to the \"Programming Language Rankings (2024 May)\" 🔗\n \n \n \n \n \n \n \n \n Link to the \"Most popular technologies\" 🔗\n \n \n \n \n \n \n \n Link to the \"RedMonk Q124 Programming Language Rankings\"🔗",
"crumbs": [
"Home",
"DAiR Workshop 2024"
]
},
{
"objectID": "index.html#commands",
"href": "index.html#commands",
"title": "DAiR Workshop 2024",
"section": "Commands",
"text": "Commands\n\nR commands are utilized within the R environment to execute specific tasks or initiate actions.\nR commands can be entered and executed in either the R command line or within R scripts.\nExecuting Code:\n\nWindows/Linux: Press Ctrl + Enter or entire R script Ctrl+Alt+R in Windows\nMac: Press Command + Enter or entire R script Command+Option+R on a Mac.\nClick the Run button of the source pane. \nTo run multiple lines of code, highlight the lines and then execute them using the appropriate method.\nThe command source(\"<file name>.R\") executes the entire saved script.\n\nAs a simple example:\n\n\nPlease enable JavaScript to experience the dynamic code cell content on this page.\n\nWhen assigning values or output from operations to a variable in R, the assignment operator <- or Alt+ - or = is placed between the variable name and the value(s) being assigned.\n\nPlease enable JavaScript to experience the dynamic code cell content on this page.\nUse source(\"\") to execute commands stored in commands.R file.\nUse sink(\"\") to redirect subsequent output from the console to a file.\nUse sink() with no arguments to restore console output.\n\n Let’s start Exercise_1!",
"crumbs": [
"Home",
"DAiR Workshop 2024"
]
},
{
"objectID": "index.html#packages-in-r",
"href": "index.html#packages-in-r",
"title": "DAiR Workshop 2024",
"section": "Packages in R",
"text": "Packages in R\n\nR packages are developed to extend the functionality of base R, benefiting a diverse community of researchers and users.\nPackages offer a streamlined method to incorporate additional command and code, data, and documentation as required.\nPackages are designed in a structured format to effectively enhance and expand R’s capabilities.\nR comes bundled with approximately 25 packages, categorized as “standard” and “recommended” packages.\nVarious platforms and repositories exist for sharing R packages, allowing for easy distribution and collaboration within the R community.\n\nCRAN (Comprehensive R Archive Network)\n\nThe Comprehensive R Archive Network (CRAN) serves as a network comprising FTP and web servers housing identical, current versions of code alongside documentation pertaining to R.\nOfficial repository for R packages.\nPackages undergo review by CRAN maintainers to ensure adherence to CRAN’s policies and guidelines.\nAs of now, the CRAN package repository boasts 20,750 available packages all of which are peer-reviewed and thoroughly tested.\nAccessible status details regarding mirrors can be found here, with priority given to selecting a site in close geographical proximity.\nCRAN Task Views aim to offer guidance by highlighting packages on CRAN relevant to specific topics.\n\nBioconductor\n\nSpecialized repository for bioinformatics and computational biology R packages.\nBioconductor conducts a rigorous review process for submitted packages.\nThe Bioconductor repository presently hosts over a thousand software packages written in R, designed for analyzing datasets of various sizes within computational biology.\n\nrOpenSci\n\nAdvances open science and reproducible research through curated and peer-reviewed R packages.\nPackages undergo open peer review by volunteers associated with rOpenSci.\n\nGitHub\n\nVersion Control Integration of R packages.\nGitHub does not enforce a formal review process for packages.\n\n\nPackage name\n\nPackage names are case-sensitive.\nEach package name is unique to itself.\n\nPackages are developed against specific versions of R available to users.\nThe “R Installation and Administration” manual provides detailed information on the necessary tools for compiling code within packages for each operating system.",
"crumbs": [
"Home",
"DAiR Workshop 2024"
]
},
{
"objectID": "index.html#utilizing-packages-in-r",
"href": "index.html#utilizing-packages-in-r",
"title": "DAiR Workshop 2024",
"section": "Utilizing Packages in R",
"text": "Utilizing Packages in R\n\nHow to install\n\nUsing the Command Line\n\n\nPlease enable JavaScript to experience the dynamic code cell content on this page.\n\nUsing the RStudio Interface\n\nAlt > Tools > Install Packages …\nOutput Pane (the lower right window) > Packages Tab > Install button > Install from [Repository (CRAN)/ Package Archive File (.tar.gz)]\n\nTo install a package from Bioconductor, follow these steps\n\nInstall “BiocManager” package.\n\nPlease enable JavaScript to experience the dynamic code cell content on this page.\nUse the `install()` function from the “BiocManager” package to install your desired package from Bioconductor\n\nPlease enable JavaScript to experience the dynamic code cell content on this page.\n\nInstall a package from Github\n\nInstall “devtools” package\n\nPlease enable JavaScript to experience the dynamic code cell content on this page.\nUse the `install_github()` function from the “devtools” package to install your desired package from GitHub.\n\nPlease enable JavaScript to experience the dynamic code cell content on this page.\nAlso you can use pak, remote or any other packages.\n\n\nUsage\n\nAfter installation the package must be loaded\n\nPlease enable JavaScript to experience the dynamic code cell content on this page.\n\nViewing Installed Packages\n\nPlease enable JavaScript to experience the dynamic code cell content on this page.\nDirectory of installed packages\n\nPlease enable JavaScript to experience the dynamic code cell content on this page.\n\nPackage Dependencies\n\n\n\n \n \n \n\n\nTo explore general information about any specific R package, the pkgnet package is a comprehensive resource. You can try it with the DESeq2 package on your own system as follows:\n\n#install.packages(\"pkgnet\")\n#BiocManager::install(\"DESeq2\")\n#library(pkgnet)\n#CreatePackageReport(pkg_name = \"DESeq2\")\n#?pkgnet\n\n\nView loaded R packages\n\nPlease enable JavaScript to experience the dynamic code cell content on this page.\nUnloading Packages\n\nPlease enable JavaScript to experience the dynamic code cell content on this page.\nRemove\n\nCommand Line\n\n\nPlease enable JavaScript to experience the dynamic code cell content on this page.\n\nOutput Pane (the lower right window) > Packages Tab > Click on the round gray X button to the right of the package version.\n\nUpdate installed packages\n\nPlease enable JavaScript to experience the dynamic code cell content on this page.\n\n\nNamespaces\nIn R, packages utilize namespaces to achieve three main objectives:\n\nEncapsulation: They allow package authors to conceal functions and data intended solely for internal use, maintaining a clean and organized structure.\nConflict Prevention: Namespaces prevent functions from malfunctioning when a user or another package author inadvertently chooses a name that conflicts with one in the package.\nScoped References: They provide a systematic method to reference an object within a specific package context.\nFor instance, the t() function in R is used for transposing matrices. If a user defines their own function named t, namespaces ensure that the package’s t() function remains accessible and does not get overridden, thus preserving functionality across the package’s operations\n\n\nIn R, namespaces are managed using two operators:\n\nDouble-Colon Operator (::): This operator selects definitions from a specific namespace. For example, base::t refers to the transpose function (t) defined in the base package. Only functions that are explicitly exported from the package can be accessed using ::.\nTriple-Colon Operator (:::): This operator acts similarly to ::, allowing access to functions and objects within a namespace. However, it also enables access to hidden objects that are not exported. It is less commonly used, as it may access objects not intended for general use.\n\nAdditionally, the getAnywhere() function in R is often preferred by users when searching for functions or objects across multiple packages. It searches through all accessible environments to find the definition of a function or object, providing flexibility in locating specific definitions regardless of their visibility or export status within packages.\n\n\nPlease enable JavaScript to experience the dynamic code cell content on this page.\n\n\n\nPlease enable JavaScript to experience the dynamic code cell content on this page.",
"crumbs": [
"Home",
"DAiR Workshop 2024"
]
},
{
"objectID": "index.html#working-directory",
"href": "index.html#working-directory",
"title": "DAiR Workshop 2024",
"section": "Working directory",
"text": "Working directory\n\nTo check the current working directory:\n\nIn RStudio, you can observe the “current working directory,” as illustrated in the image above or using getwd().\n\n\nTo set the working directory to a specific target directory:\n\nsetwd(\"Target_Directory\")\n\nAlternatively, navigate to Session > Set Working Directory > Choose Directory ( CMD+Shift+H/Ctrl+Shift+H)\nTo create an empty file or directory in R, you can indeed use file.create() and dir.create() :\n\nFile Permissions: The ability to create files and directories depends on your operating system’s permissions.\n\n\n\nExisting Files/Directories: If the file or directory already exists, file.create() or dir.create() will not overwrite it but will return FALSE.\nfile.remove(): Removes files.\n\n\n\nunlink(): Removes files and directory trees.\nlist.files() or dir(): Lists files in a directory.\n\n\n\nlist.dirs(): Lists directories in a directory.\nfile.info(): Retrieves information about a file.\nfile.copy(): Copies files.\nfile.choose(): Allows interactive file selection.\n\n\n\nchoose.files(), choose.dir(): More versatile functions for file and directory selection on Windows.\nfile.show(): Displays files.\n\n\n\nfile.edit(): Edits files using appropriate R console facilities.\n\n\n\nPlease enable JavaScript to experience the dynamic code cell content on this page.\n\n\nrecursive = TRUE: This option in unlink() ensures that the directory and all its contents (subdirectories and files) are removed.\n\nbasename(): Returns the file name component of a file path.\ndirname(): Returns the directory component of a file path.\nSys.info(), system() and system2() Functions:\n\n`system(command, ...): Invokes a system command and optionally collects its output. On non-Windows systems, it typically invokes a shell to run the command.\nsystem2(command, args, ...):Allows explicit passing of command arguments separately from the command itself.\nsystem() behaves differently because of underlying API differences. Use shell() to invoke a shell explicitly.\n\n\n Let’s start Exercise_2!\n\n\n In our previous session, we successfully covered these key tasks:\n We walked through the process of installing both R and RStudio on different operating systems.\n We explored the RStudio interface, including the source pane, console, environment pane, and file pane.\n We practiced writing and executing basic R commands in the console and script editor.\n We learned how to install packages from CRAN and load them into our R sessions.\n We also discussed how to check for discrepancies and troubleshoot common installation issues.\n\n We became familiar with the concept of the working directory in R and how to navigate and manipulate files and directories using functions.",
"crumbs": [
"Home",
"DAiR Workshop 2024"
]
},
{
"objectID": "index.html#r-ai-api",
"href": "index.html#r-ai-api",
"title": "DAiR Workshop 2024",
"section": "R & AI-API",
"text": "R & AI-API\nIf you’re interested in coding in R using an Artificial Intelligence platform, there are several options available such as RTutor, gptstudio, gpttools.\n“RTutor”, for instance:\n\nRTutor is an AI-powered app designed to quickly generate and test R code.\nIt harnesses API calls to models like OpenAI’s ChatGPT, enabling rapid generation and testing of R code.\nRTutor translates natural language into executable R scripts, seamlessly integrating with the Shiny platform.\nAdditionally, it supports the generation of R Markdown source files and HTML reports for comprehensive documentation and presentation of your work.\n\n\n\n \n \n \n \n \n \n \n\n\nTo get started with using OpenAI’s services in RStudio, you need to set up an API key:\n\nSign Up for OpenAI:\n\nGo to the OpenAI sign-up page.\nFollow the instructions to create an account.\n\nGenerate an OpenAI API Key\n\nLog In to OpenAI:\n\nGo to the OpenAI login page and log in with your account.\n\nCreate an API Key:\n\nNavigate to the API key section in your OpenAI account dashboard.\nClick on “Create new secret key” to generate a new API key.\nCopy the generated API key. You will need this key to configure the package in RStudio.\n\n\nSet the API key as an environment variable by adding it to your .Renviron file or setting it directly in your R session.\n\nrequire(usethis)\nedit_r_environ()\nor\nusethis::edit_r_environ()\nOPENAI_API_KEY=\"your_openai_api_key_here\"\nor\nSys.setenv(openai_secret_key = \"\")\n\n#To combine the data from list_models() into a single data frame using dplyr::bind_rows():\n\nlist_models()$data %>% \n dplyr::bind_rows()\n\nThis package is an SDK for Open AI’s API.",
"crumbs": [
"Home",
"DAiR Workshop 2024"
]
},
{
"objectID": "index.html#oop",
"href": "index.html#oop",
"title": "DAiR Workshop 2024",
"section": "OOP",
"text": "OOP\n\nR indeed supports object-oriented programming (OOP) features alongside its functional programming characteristics.\nOOP is a programming paradigm that revolves around the concept of objects.\nCentral to any object-oriented language are the concepts of class and of methods.\nR supports OOP through systems such as S3, S4, and R6, which allow users to create and manipulate objects and define classes.\nA class is a definition of an object.\nTypically a class contains several slots that are used to hold class-specific information.\nR does not allow direct access to the computer’s memory. It R abstracts memory management from the user, providing a higher-level interface to manage data through objects and data structures.\nObjects are instances of classes that encapsulate both data (attributes or properties) and methods (functions associated with the object).\nProgramming is based on objects.\n\nPlease enable JavaScript to experience the dynamic code cell content on this page.\n\n\nObjects in R\n\nSo, everything in R is an object.\nAn R object’s data type, defines how its values are stored in the computer. For instance fruit in the above example is an object which is class of function.\n\n\n\n Some of R Object Types\n\n\n\n\n\n\nType\nDescription\n\n\nNULL\nNULL\n\n\nsymbol\na variable name\n\n\npairlist\na pairlist object (mainly internal)\n\n\nFunction closure\na function\n\n\nenvironment\nan environment\n\n\nlanguage\nan R language construct\n\n\nbuiltin\nan internal function that evaluates its arguments like `sum()`, `mean()`,`length()`\n\n\nlogical\na vector containing logical values\n\n\ninteger\na vector containing integer values\n\n\ndouble\na vector containing real values\n\n\ncomplex\na vector containing complex values\n\n\ncharacter\na vector containing character values\n\n\n...\nthe special variable length argument\n\n\nany\na special type that matches all types: there are no objects of this type\n\n\nexpression\nan expression object\n\n\nlist\na list\n\n\n\n\n\n\n\nBy the mode of an object we mean the basic type of its fundamental constituents.\nAnother property of every object is its length.\n\n\n\n\n\n\n\n\n\n\n\n\n\nBased on the figures above, it’s evident that R’s capability to store analysis results in objects enables users to extract specific data for further analyses. This flexibility makes R a powerful tool, for example in extracting and manipulating specific subsets of genomic data for downstream analyses. In contrast, graphical-based statistical software like SPSS or GraphPad often requires more manual steps and restricts flexibility in data handling and analysis workflows.\n\n\n\n\n\n\n\n\n\nSchematic of R working\n\n\n\n\n\n\n\n\n\n\n\n\n\nData Type In R\n\n\n\nclass\ntypeof\nst.mode\nmode\nis.double\nis.integer\nis.numeric\nis.logical\nis.character\nis.vector\n\n\n\n\ninteger_vector\ninteger\ninteger\ninteger\nnumeric\nFALSE\nTRUE\nTRUE\nFALSE\nFALSE\nTRUE\n\n\nnumeric_vector\nnumeric\ndouble\ndouble\nnumeric\nTRUE\nFALSE\nTRUE\nFALSE\nFALSE\nTRUE\n\n\ncharacter_vector\nlogical\nlogical\nlogical\nlogical\nFALSE\nFALSE\nFALSE\nTRUE\nFALSE\nTRUE\n\n\ninteger_array\narray\ninteger\ninteger\nnumeric\nFALSE\nTRUE\nTRUE\nFALSE\nFALSE\nFALSE\n\n\nnumeric_array\narray\ndouble\ndouble\nnumeric\nTRUE\nFALSE\nTRUE\nFALSE\nFALSE\nFALSE\n\n\nmatrix\nc(\"matrix\", \"array\")\ninteger\ninteger\nnumeric\nFALSE\nTRUE\nTRUE\nFALSE\nFALSE\nFALSE\n\n\ndata_frame\ndata.frame\nlist\nlist\nlist\nFALSE\nFALSE\nFALSE\nFALSE\nFALSE\nFALSE\n\n\nlist\nlist\nlist\nlist\nlist\nFALSE\nFALSE\nFALSE\nFALSE\nFALSE\nTRUE\n\n\nfactor\nfactor\ninteger\ninteger\nnumeric\nFALSE\nFALSE\nFALSE\nFALSE\nFALSE\nFALSE\n\n\nformula\nformula\nlanguage\nlanguage\ncall\nFALSE\nFALSE\nFALSE\nFALSE\nFALSE\nFALSE\n\n\nclosure_function\nfunction\nclosure\nfunction\nfunction\nFALSE\nFALSE\nFALSE\nFALSE\nFALSE\nFALSE\n\n\nbuiltin_function\nfunction\nbuiltin\nfunction\nfunction\nFALSE\nFALSE\nFALSE\nFALSE\nFALSE\nFALSE\n\n\nspecial_function\nfunction\nspecial\nfunction\nfunction\nFALSE\nFALSE\nFALSE\nFALSE\nFALSE\nFALSE\n\n\nLanguage_objects\ncall\nlanguage\nlanguage\ncall\nFALSE\nFALSE\nFALSE\nFALSE\nFALSE\nFALSE\n\n\nExpression_objects\nexpression\nexpression\nexpression\nexpression\nFALSE\nFALSE\nFALSE\nFALSE\nFALSE\nTRUE\n\n\nSymbol_objects\nname\nsymbol\nsymbol\nname\nFALSE\nFALSE\nFALSE\nFALSE\nFALSE\nFALSE\n\n\nNULL\nNULL\nNULL\nNULL\nNULL\nFALSE\nFALSE\nFALSE\nFALSE\nFALSE\nFALSE\n\n\npairlist\npairlist\npairlist\npairlist\npairlist\nFALSE\nFALSE\nFALSE\nFALSE\nFALSE\nFALSE\n\n\nlogical\nlogical\nlogical\nlogical\nlogical\nFALSE\nFALSE\nFALSE\nTRUE\nFALSE\nTRUE\n\n\nraw\nraw\nraw\nraw\nraw\nFALSE\nFALSE\nFALSE\nFALSE\nFALSE\nTRUE\n\n\nenvironment\nenvironment\nenvironment\nenvironment\nenvironment\nFALSE\nFALSE\nFALSE\nFALSE\nFALSE\nFALSE\n\n\n\n\n\n\n\n\n\nThe unclass() function in R is used to temporarily remove the effects of class from an object, treating it as its underlying data structure.\n\n\n\nPlease enable JavaScript to experience the dynamic code cell content on this page.\n\n\nHow to use unclass():\n\nInspection and Debugging:\n\nTo inspect the raw data inside an object, ignoring the class-specific methods and attributes.\nUseful for debugging when you want to see how data is stored without the formatting or behavior imposed by the object’s class.\n\nData Manipulation:\n\nTo perform operations that are easier or only possible on the object’s underlying structure rather than the object with its class.\nExample: Modifying the underlying numeric values of a factor without dealing with its factor levels.\n\nPerformance Optimization:\n\nWhen performing operations where the class attributes are unnecessary and could add overhead, removing the class temporarily can sometimes make the code simpler and faster.\n\nClass Conversion:\n\nAs an intermediate step in converting an object from one class to another by stripping the original class and then assigning a new class.\n\n\nPlease enable JavaScript to experience the dynamic code cell content on this page.\n\n\n\nPlease enable JavaScript to experience the dynamic code cell content on this page.\n\n\n\n\n\n\nAttributes in R Objects\n\nR objects have additional metadata with extra piece of information known as “attributes”.\nAll objects except NULL may contain one or more attributes attached to them.\nAttributes are stored as name=value pairs in a pairlist.\nThe attributes() function in R allows you to access and manipulate these attributes associated with an object.\nWhy are attributes needed in data science?\nFor instance, a linear regression model attributes:\n\n\nPlease enable JavaScript to experience the dynamic code cell content on this page.\n\nAlthough, it is possible to add attribute to the NULL object in this method:\n\n\nPlease enable JavaScript to experience the dynamic code cell content on this page.\n\nThere is also a facility for converting functions to and from list structures using as.list and as.function.\nA special object called NULL is used whenever there is a need to indicate or specify that an object is absent.\nNULL should not be confused with a vector or list of zero length.\nUse ls() or objects() to list all objects currently stored in your R workspace.\nUse rm() to remove specific objects from your R workspace.\nTo remove all objects in the workspace, you can use:\nrm(list = ls()).\nA vector is the most common and fundamental data structure in R.\nThere are two main types of vectors:\n\nAtomic Vectors: These are homogeneous collections of data that can only contain elements of the same data type, such as numeric, character, logical, etc.\nLists: Lists are heterogeneous collections that can contain elements of different types, including other lists and even functions.\nvector() function produces a ‘simple’ vector of the given length and mode.\n\n\n\n\nIn R, symbols or variables act as references to these objects, allowing you to manipulate and analyze the data stored within them.\n\nPlease enable JavaScript to experience the dynamic code cell content on this page.\n\nAs in the S language, vectors with integer or real values are both of mode “numeric”, so their storage modes need to be distinguished.\n\nPlease enable JavaScript to experience the dynamic code cell content on this page.\n\nin other word mode() function it will not distinguish integers from doubles.\nIn the case of the basic vector types one can access the i-th element using x[i], but there is also indexing of lists, matrices, and multi-dimensional arrays.",
"crumbs": [
"Home",
"DAiR Workshop 2024"
]
},
{
"objectID": "index.html#methods",
"href": "index.html#methods",
"title": "DAiR Workshop 2024",
"section": "Methods",
"text": "Methods\n\nComputations are carried out via methods.\nMethods are basically functions that are specialized to carry out specific calculations on objects, usually of a specific class.\nThis is what makes the language object oriented.\n\n\n\n\nSome groups of R Functions\n\n\n\n\n\n\nGroup\nFunction Names\nSummary of Function\n\n\nMath\nabs, acos, acosh, asin, asinh, atan, atanh, ceiling, cos, cosh, cospi, cumsum, exp, floor, gamma, lgamma, log, log10, round, signif, sin, sinh, sinpi, tan, tanh, tanpi, trunc\nMathematical functions for various operations like trigonometry, logarithms, rounding, etc.\n\n\nSummary\nall, any, max, min, prod, range, sum\nFunctions to compute summary statistics like minimum, maximum, sum, etc., across data.\n\n\nOps\n+, -, *, /, ^, <, >, <=, >=, !=, ==, %%, %/%, &, |, !\nOperators for arithmetic, comparison, logical operations, and special operators like modulus and integer division.\n\n\n\n\n\n\n\n\nFunction\nDescription\nExample\n\n\n+\nAddition of values\n5 + 3 = 8\n\n\n−\nSubtraction of values\n2 − 4 = −2\n\n\n*\nMultiplication of values\n8 * (−2) = −16\n\n\n/\nDivision of values\n−16 / 16 = −1\n\n\n%%\nmodulo\n100 %% 15 = 10\n\n\n%/%\ninteger division\n100 %/% 15 = 6\n\n\n!,&,|,xor\nNegation, Logical “and”, Logical “or”, Logical “exclusive or”\n!x == 20,x >= 20 & x < 35\n\n\nx %in% y\nValue matching; character\n! x %in% y\n\n\nsqrt()\nSquare root of a number\nsqrt(9) = 3\n\n\n(y)^(1 / x)\nx-th root of the number y\n7776^(1/5) = 6\n\n\n^\nPower of a number\n3^3 = 27\n\n\nlog()\nNatural logarithm\nlog(120) = 4.79\n\n\nexp()\nExponential function\nexp(10) = 22,026.47\n\n\nmean()\nCalculates the average of a numeric vector\nmean(c(1, 2, 3)) = 2\n\n\nmedian()\nFinds the middle value of a numeric vector\nmedian(c(1, 3, 5)) = 3\n\n\nsum()\nComputes the total sum of a numeric vector\nsum(c(1, 2, 3)) = 6\n\n\nmin()\nIdentifies the smallest value in a numeric vector\nmin(c(1, 2, 3)) = 1\n\n\nmax()\nIdentifies the largest value in a numeric vector\nmax(c(1, 2, 3)) = 3\n\n\nsd()\nCalculates the standard deviation of a numeric vector\nsd(c(1, 2, 3)) = 1\n\n\nvar()\nComputes the variance of a numeric vector\nvar(c(1, 2, 3)) = 1\n\n\nquantile()\nCalculates the specified quantiles of a numeric vector\nquantile(c(1, 2, 3), probs = 0.5) = 2\n\n\nlength()\nDetermines the number of elements in a vector\nlength(c(1, 2, 3)) = 3\n\n\nrange()\nReturns the minimum and maximum values of a numeric vector\nrange(c(1, 2, 3)) = 1 3\n\n\nIQR()\nComputes the interquartile range of a numeric vector\nIQR(c(1, 2, 3, 4, 5)) = 2",
"crumbs": [
"Home",
"DAiR Workshop 2024"
]
},
{
"objectID": "index.html#control-statement",
"href": "index.html#control-statement",
"title": "DAiR Workshop 2024",
"section": "Control Statement",
"text": "Control Statement\nControl statement are fundamental aspect of all programming languages, including R.\n\nControl structures in R allow you to manage the flow of execution for a series of expressions.\nThey enable you to add logic to your R code, making it more dynamic and responsive to different inputs or data features.\nBy using control structures, you can ensure that different R expressions are executed based on certain conditions, rather than always running the same code each time.\nThey are typically used in functions or longer expressions rather than in interactive sessions.\n\nYou can also use control structures outside of functions to understand their behavior and become comfortable with them.\n\nHere are some commonly used control structures:\n\nfor loop: Used to execute a loop a specified number of times.\nbreak : Used to terminate the execution of a loop prematurely.\nnext : Used to skip the current iteration of a loop and proceed to the next iteration.\nwhile : Used to execute a loop as long as a condition remains true.\nif and else : Used to test a condition and execute code based on the result.\nrepeat :Used to execute an infinite loop, which must be explicitly terminated with a break statement.\n\n\n\nLoops\n\nR excels at handling repetitive tasks through loops.\nLoops allow you to repeat a set of operations multiple times or until a specified condition is met.\nThere are three main types of loops in R:\n\nThe for loop :\n\nFor loops are indeed versatile and commonly used in R for iterating over sequences or performing repetitive tasks.\nWhile other loop constructs like while loops and repeat loops have their specific use cases, for loops often suffice in practice.\n\nThe while loop\nThe repeat loop.\n\n\n\nFor Loop\nIn R, for loops are a fundamental construct used to iterate over elements of objects like lists or vectors. For example:\nfor each character i in the sequence ‘A’ to ‘J’ do // execute code within curly braces end loop\n\n\nPlease enable JavaScript to experience the dynamic code cell content on this page.\n\nWhile other looping constructs exist, for loops are typically adequate for most data analysis tasks due to their simplicity and effectiveness.\n\n\nPlease enable JavaScript to experience the dynamic code cell content on this page.\n\n\n\nPlease enable JavaScript to experience the dynamic code cell content on this page.",
"crumbs": [
"Home",
"DAiR Workshop 2024"
]
},
{
"objectID": "index.html#nested-for-loops",
"href": "index.html#nested-for-loops",
"title": "DAiR Workshop 2024",
"section": "Nested for loops",
"text": "Nested for loops\nWe can nest for loops inside one another.\nThis allows you to perform more complex iterations and computations where multiple levels of looping are required.\n\nNested for loops involve placing one or more for loops inside the body of another for loop.\nEach inner loop executes its entire cycle for every iteration of the outer loop.\nThis nested structure is useful for iterating over multidimensional data structures like matrices or performing repetitive tasks that involve multiple levels of iteration.\n\n\nPlease enable JavaScript to experience the dynamic code cell content on this page.\n\n\n\nif statement\n\n\nPlease enable JavaScript to experience the dynamic code cell content on this page.\n\n\n\nelse statement\n\n\nPlease enable JavaScript to experience the dynamic code cell content on this page.\n\nLet’s proceed with Exercise 3.",
"crumbs": [
"Home",
"DAiR Workshop 2024"
]
},
{
"objectID": "index.html#functions",
"href": "index.html#functions",
"title": "DAiR Workshop 2024",
"section": "Functions",
"text": "Functions\nTo comprehend functions in R thoroughly, it’s essential to grasp two key concepts:\n\nFunction Components: Functions consist of three primary components:\n\nFormals (formals()):\n\nThis represents the list of arguments defined when the function is created. Arguments determine how you call and pass data into the function. They are inputs provided to the function.\n\nBody (body()):\n\nThe body contains the actual code that executes when the function is called. It defines what the function does with the provided arguments. The sequence of expressions that define what the function does.\n\nEnvironment (environment()):\n\nThe environment specifies the context or scope in which the function operates. It dictates how the function accesses and interacts with data and other objects.\n\n\n\nThe environment is implicitly determined based on where the function is defined. If the function is defined within the global environment, it inherits that environment unless specified otherwise..\n\n\nPrimitive Base Functions: Despite the general rule that functions are defined in R, there are exceptions. A subset of functions known as “primitive” base functions is implemented directly in C for efficiency reasons.\n\nSuch as sum() as type builtin and [ as type special,which are exceptions to the standard function structure.\nThey directly call C code for execution and offering optimized performance for basic operations like summing elements or extracting subsets of data.\nHence, when you check their attributes using formals(), body(), or environment() functions, they typically return NULL because these attributes are not applicable to primitive functions\nPrimitive functions in R are typically found in the base package of R.\n\nFunctions as Objects: Similar to vectors and other data types, functions are objects in R.\n\nR does not require special syntax for defining and naming functions.\n\n\nPlease enable JavaScript to experience the dynamic code cell content on this page.\n\nYou create a function object using the function keyword and then bind it to a name using the assignment operator <-.\nThis flexibility allows for dynamic and powerful programming capabilities within R.\nsrcref is useful for printing or displaying the original source code that was used to create the function.\nAnonymous functions, also known as lambda functions, e useful in situations where you need a function for a short period or when it’s not necessary to assign a name.\n\n\nPlease enable JavaScript to experience the dynamic code cell content on this page.\n\n\nThis example demonstrate the use of function lapply along with anonymous functions defined using function(x).\n\n\nPlease enable JavaScript to experience the dynamic code cell content on this page.\n\n\nPutting functions in a list can be very useful, especially when you need to store multiple functions together for organizational purposes or to pass them as arguments to other functions.\n\n::: {.cell}\n\n```{.webr .cell-code}\n# Define some example functions\nsquare <- function(x) x^2\ncube <- function(x) x^3\nsqrt <- function(x) x^0.5\n\n# Create a list of functions\nfunction_list <- list(\n square = square,\n cube = cube,\n sqrt = sqrt\n)\n\n# Access and use functions from the list\nfunction_list$square(5)\nfunction_list$cube(4)\nfunction_list$sqrt(16)\n```\n:::\n\n\n- In the above example:\n\n - We define three functions (`square`, `cube`, and `sqrt`).\n\n - We create a list `function_list` containing these functions, where each function is assigned a name within the list (`square`, `cube`, `sqrt`).\n\n - We then call each function from the list using `$` notation (`function_list$square`, `function_list$cube`, `function_list$sqrt`).\n\n\nIf we have the arguments for a function already stored in a data structure, such as a list or a vector, we can still call the function using the do.call() function in R.\n\n\nPlease enable JavaScript to experience the dynamic code cell content on this page.\n\n\nUnderstanding these aspects is fundamental for mastering function usage and manipulation in R.\nBase R provides two ways to compose multiple function calls: nesting and piping.\n\nNesting\nIt is straightforward but can become unwieldy with complex chains of functions.\n\n\nPlease enable JavaScript to experience the dynamic code cell content on this page.\n\nIn this example:\n\nmean(data) computes the mean of the data.\ndata - mean(data) computes the deviations from the mean.\n(data - mean(data))^2 squares the deviations.\nmean((data - mean(data))^2) computes the mean of the squared deviations (variance).\nsqrt(mean((data - mean(data))^2)) takes the square root of the variance to get the standard deviation.\n\nPiping\nOffers improved readability and maintainability by breaking down complex operations into a sequence of simple steps.\n\nintroduced in the magrittr package and later incorporated into dplyr.\nThe pipe operator %>% passes the result of one function call as the first argument to the next function.\n\n\nPlease enable JavaScript to experience the dynamic code cell content on this page.\n\nIn this example:\n\ndata %>% starts the pipeline with the data.\n-(mean(.)) subtracts the mean of data from each element.\n^(2) squares each deviation.\nmean() computes the mean of the squared deviations.\nsqrt() takes the square root of the variance to get the standard deviation."
},
{
"objectID": "index.html#vector",
"href": "index.html#vector",
"title": "DAiR Workshop 2024",
"section": "Vector",
"text": "Vector\n\nVectors are single-dimensional, homogeneous data structures.\nSo, Vectors can only contain elements of one type!\nTo create a vector, concatenating values using the c() function.\n\n\n\nThis build of rgl does not include OpenGL functions. Use\n rglwidget() to display results, e.g. via options(rgl.printRglwidget = TRUE).\n\n\nnull \n 1 \n\n\n\n\n\n\n\nPlease enable JavaScript to experience the dynamic code cell content on this page.\n\nSome important functions are: c() , vctor(),length(), class(), typeof(), attributes(), is.double(), is.numeric(), is.integer(), is.logical(), is.character(), is.vector()\n\nPlease enable JavaScript to experience the dynamic code cell content on this page.\nNumeric sequences:\n\nRegular sequences can be created using the function seq() and its shortcuts seq.int(), seq_along(), and seq_len().\nnumeric or integer values between two well defined points (from and to) with an equidistant spacing.\n\nPlease enable JavaScript to experience the dynamic code cell content on this page.\n\nCharacter Sequences:\n\nNeed the letters of the alphabet use LETTERS and letters\n\nReplicating elements\n\nReplicate one specific value n times.\nGiven an existing vector: Replicate each element n times.\nGiven an existing vector: Replicate the entire vector n times.\nGiven an existing vector: Replicate the elements different amount of times.\n\nPlease enable JavaScript to experience the dynamic code cell content on this page.\nrep.int()\n\nIf we combine elements of different types, R has to convert all elements into the same type/class as vectors can only contain elements of one type. This is called ‘coercion’:\n\n\nImplicit coercion: R chooses the best option.\n\n\nPlease enable JavaScript to experience the dynamic code cell content on this page.\n\nEvery numeric value equal to 0/0L converted to logical results in FALSE.\nEvery numeric value not equal to 0/0L converted to logical results in TRUE.\nEvery TRUE converted to numeric will be 1 (or 1L).\nEvery FALSE converted to numeric will be 0 (or 0L).\n\nPlease enable JavaScript to experience the dynamic code cell content on this page.\nExplicit coercion: we force something to be of a different type:\nas.integer() , as.numeric() ,as.character() ,as.logical() ,as.matrix().\n\nPlease enable JavaScript to experience the dynamic code cell content on this page.\nIf R is not able to convert elements, it will return NA\n\nas.integer(x)\nx <- c(\"1\", \"100\", \"a\", \"b\", \"33\")\nas.integer(x)\n\n\nMultiply a sequence with a scalar scalar (a single number)\n\nPlease enable JavaScript to experience the dynamic code cell content on this page.\nv\n\nPlease enable JavaScript to experience the dynamic code cell content on this page.\n\n\nPlease enable JavaScript to experience the dynamic code cell content on this page.\n\n\n\nnull \n 3 \n\n\n\n\n\n\n\n\nnull \n 5 \n\n\n\n\n\n\n\n\nnull \n 7 \n\n\n\n\n\n\n\nMissing values\n\nMissing values in R still have a class.(missing numeric, integer, logical, or character missing values.)\nNaN: Mathematically not defined (and always of class numeric).\n\nPlease enable JavaScript to experience the dynamic code cell content on this page.\nNA: Missing value, NA’s still have classes!\nNaN is also NA but not vice versa."
},
{
"objectID": "index.html#objects",
"href": "index.html#objects",
"title": "DAiR Workshop 2024",
"section": "Objects",
"text": "Objects\n\nPlease enable JavaScript to experience the dynamic code cell content on this page."
},
{
"objectID": "index.html#footnotes",
"href": "index.html#footnotes",
"title": "DAiR Workshop 2024",
"section": "Footnotes",
"text": "Footnotes\n\n\nAssociation for Computing Machinary↩︎\nSoftware release life cycle↩︎\nR (programming language)↩︎\nAPI↩︎",
"crumbs": [
"Home",
"DAiR Workshop 2024"
]
},
{
"objectID": "Exercise.html",
"href": "Exercise.html",
"title": "Exersices",
"section": "",
"text": "Bioinformatics and Data Science Summer Workshops 2024\n\n\n\n \n \n \n \n \n \n \n Author: Dr. Hamed Abdollahi \n PI: Dr. Homayoun Valafar \n \n \n\n\n\n\n \n Exercise I\n \n \n Exercise II\n \n \n Exercise III \n \n \n Exercise IV \n \n \n Exercise V \n \n \n \n \n Exercise VI \n \n \n Data Wrangling Exercises.docx"
},
{
"objectID": "Exercises/Exercise_1.html",
"href": "Exercises/Exercise_1.html",
"title": "Exercise_1",
"section": "",
"text": "Objective: We will practice scripting commands in R, including file creation, editing, sourcing scripts, and using sink() to capture and redirect output.\nProblem Statement:\nPerform the following tasks in R:\n\nCreate a script file named command_example.R.\nEdit the script file using file.edit() to add the following content:\nCopy & paste code from here.\nExecute the script file command_example.R and print the results.\nRedirect the output of the script to a text file named result_command_example.txt.\nStop redirecting output.\n\nHints:\n\nUse file.create() to create the script file.\nUse file.edit() to modify the script file with the provided content.\nUse source(\"\") to execute the script and display its output in the console.\nUse sink(\"file_name.txt\") to redirect R output to a text file.\nUse sink() without arguments to stop redirecting output.\n\nChallenge Question: How would you modify the script to handle errors or warnings that might occur during script execution? What methods can you use to capture and handle such messages effectively?\nThis exercise will help students practice fundamental scripting tasks in R, including file handling, sourcing scripts, and managing script output using sink(), preparing them for more complex data processing and automation tasks in R."
},
{
"objectID": "about.html",
"href": "about.html",
"title": "About",
"section": "",
"text": "Author: Dr. Hamed Abdollahi \n PI: Dr. Homayoun Valafar\nAbout this Site\nThe intention behind preparing this site is to cover all the topics of the Workshop on Data Analytics in R. This workshop is a 2024 summer course in Bioinformatics and Data Science that can be attended in person at the University of South Carolina in Columbia, SC, or virtually (synchronously). The course is free for all affiliate members of SC INBRE."
},
{
"objectID": "about.html#bioinformatics-core",
"href": "about.html#bioinformatics-core",
"title": "About",
"section": "Bioinformatics Core",
"text": "Bioinformatics Core\n\nThe National Institutes of Health (NIH) established the IDeA Networks of Biomedical Research Excellence (INBRE) to increase research capacity by programmatic expansion and networking of research activities of faculty and students at academic institutions throughout certain targeted states – with South Carolina being one of those states. \nSC INBRE is achieving that goal by supporting the career development of faculty and hands-on research training of students at our network institutions through annual workshops for faculty and students focusing on career development, mentoring and other relevant topics, as well as funding opportunities available to any faculty at SC INBRE’s network institutions. \nSC INBRE Cycle IV began on September 1, 2020 and includes a statewide network of 14 member institutions, two outreach institutions and two alumni institutions. Member and outreach/alumni institutions incorporate South Carolina’s three Comprehensive Research Universities and 15 of the state’s Primarily Undergraduate Institutions, including three Historically Black Colleges and Universities. SC INBRE is administered at the University of South Carolina School of Medicine Columbia. INBRE IV renewal announcement.\n\n\n\nThe goal of the SC INBRE Bioinformatics Core is to increase the National \nInstitutes of Health research capacity of the state by providing \nbioinformatics support to faculty, postdoctoral fellows, graduate \nstudents, and undergraduate students of the lead and partner \ninstitutions.\n\n\nFor more info, contact:\n\nDr. Homayoun Valafar\n\nUniversity of South Carolina, (803) 777-2404, Email."
},
{
"objectID": "Scripts/Script_4.html",
"href": "Scripts/Script_4.html",
"title": "Script_3",
"section": "",
"text": "x <- c(\"Apple\", \"Strawberry\", \"Cherry\")\n\nfor (fruit in x)\n print(paste(\"I like\", fruit))# without curly braces if the for loop is a single statement.\n\n[1] \"I like Apple\"\n[1] \"I like Strawberry\"\n[1] \"I like Cherry\"\n\n\n\nfor (i in LETTERS[1:10]) {\n print(i)\n}\n\n[1] \"A\"\n[1] \"B\"\n[1] \"C\"\n[1] \"D\"\n[1] \"E\"\n[1] \"F\"\n[1] \"G\"\n[1] \"H\"\n[1] \"I\"\n[1] \"J\"\n\n\n\nx <- LETTERS[1:10]#Vector Definition\nfor(i in 5:9) {#For Loop\n ## Indexing 'x'\n print(x[i]) \n}\n\n[1] \"E\"\n[1] \"F\"\n[1] \"G\"\n[1] \"H\"\n[1] \"I\"\n\n\nThe seq_along() function is quite useful in R for iterating over elements of an object.\nIt is use to generate a sequence of integers that correspond to the indices of an object. So it is based on the length of the object.\n\nx <- c(\"A\", \"B\", \"C\", \"D\", \"E\")\n\nfor (i in seq_along(x)) {\n print(paste(\"Index\", i, \":\", x[i]))\n}\n\n[1] \"Index 1 : A\"\n[1] \"Index 2 : B\"\n[1] \"Index 3 : C\"\n[1] \"Index 4 : D\"\n[1] \"Index 5 : E\"\n\n\nUsage in genomics\n\n# Load the iris dataset (if not already loaded)\ndata(iris)\nstr(iris)\n\n'data.frame': 150 obs. of 5 variables:\n $ Sepal.Length: num 5.1 4.9 4.7 4.6 5 5.4 4.6 5 4.4 4.9 ...\n $ Sepal.Width : num 3.5 3 3.2 3.1 3.6 3.9 3.4 3.4 2.9 3.1 ...\n $ Petal.Length: num 1.4 1.4 1.3 1.5 1.4 1.7 1.4 1.5 1.4 1.5 ...\n $ Petal.Width : num 0.2 0.2 0.2 0.2 0.2 0.4 0.3 0.2 0.2 0.1 ...\n $ Species : Factor w/ 3 levels \"setosa\",\"versicolor\",..: 1 1 1 1 1 1 1 1 1 1 ...\n\nlibrary(dplyr)\n\nWarning: package 'dplyr' was built under R version 4.3.2\n\n\n\nAttaching package: 'dplyr'\n\n\nThe following objects are masked from 'package:stats':\n\n filter, lag\n\n\nThe following objects are masked from 'package:base':\n\n intersect, setdiff, setequal, union\n\nglimpse(iris)\n\nRows: 150\nColumns: 5\n$ Sepal.Length <dbl> 5.1, 4.9, 4.7, 4.6, 5.0, 5.4, 4.6, 5.0, 4.4, 4.9, 5.4, 4.…\n$ Sepal.Width <dbl> 3.5, 3.0, 3.2, 3.1, 3.6, 3.9, 3.4, 3.4, 2.9, 3.1, 3.7, 3.…\n$ Petal.Length <dbl> 1.4, 1.4, 1.3, 1.5, 1.4, 1.7, 1.4, 1.5, 1.4, 1.5, 1.5, 1.…\n$ Petal.Width <dbl> 0.2, 0.2, 0.2, 0.2, 0.2, 0.4, 0.3, 0.2, 0.2, 0.1, 0.2, 0.…\n$ Species <fct> setosa, setosa, setosa, setosa, setosa, setosa, setosa, s…\n\ncolnames(iris)\n\n[1] \"Sepal.Length\" \"Sepal.Width\" \"Petal.Length\" \"Petal.Width\" \"Species\" \n\ndim(iris)\n\n[1] 150 5\n\n# Create an empty vector to store means\nmean_iris <- NULL\n# Loop through columns of the dataset\nfor(i in seq_along(iris[,1])) {\n mean_iris <- c(mean_iris,mean(as.numeric(iris[i, 1:3])))\n}\n# Print the first 8 elements of myve\nprint(mean_iris[1:8])\n\n[1] 3.333333 3.100000 3.066667 3.066667 3.333333 3.666667 3.133333 3.300000\n\n\nQuestion:\n\nWhat is the differences between str() and glimpse()?\nAnd what is another function similar to them?"
},
{
"objectID": "Scripts/Script_4.html#r-markdown",
"href": "Scripts/Script_4.html#r-markdown",
"title": "Script_3",
"section": "",
"text": "x <- c(\"Apple\", \"Strawberry\", \"Cherry\")\n\nfor (fruit in x)\n print(paste(\"I like\", fruit))# without curly braces if the for loop is a single statement.\n\n[1] \"I like Apple\"\n[1] \"I like Strawberry\"\n[1] \"I like Cherry\"\n\n\n\nfor (i in LETTERS[1:10]) {\n print(i)\n}\n\n[1] \"A\"\n[1] \"B\"\n[1] \"C\"\n[1] \"D\"\n[1] \"E\"\n[1] \"F\"\n[1] \"G\"\n[1] \"H\"\n[1] \"I\"\n[1] \"J\"\n\n\n\nx <- LETTERS[1:10]#Vector Definition\nfor(i in 5:9) {#For Loop\n ## Indexing 'x'\n print(x[i]) \n}\n\n[1] \"E\"\n[1] \"F\"\n[1] \"G\"\n[1] \"H\"\n[1] \"I\"\n\n\nThe seq_along() function is quite useful in R for iterating over elements of an object.\nIt is use to generate a sequence of integers that correspond to the indices of an object. So it is based on the length of the object.\n\nx <- c(\"A\", \"B\", \"C\", \"D\", \"E\")\n\nfor (i in seq_along(x)) {\n print(paste(\"Index\", i, \":\", x[i]))\n}\n\n[1] \"Index 1 : A\"\n[1] \"Index 2 : B\"\n[1] \"Index 3 : C\"\n[1] \"Index 4 : D\"\n[1] \"Index 5 : E\"\n\n\nUsage in genomics\n\n# Load the iris dataset (if not already loaded)\ndata(iris)\nstr(iris)\n\n'data.frame': 150 obs. of 5 variables:\n $ Sepal.Length: num 5.1 4.9 4.7 4.6 5 5.4 4.6 5 4.4 4.9 ...\n $ Sepal.Width : num 3.5 3 3.2 3.1 3.6 3.9 3.4 3.4 2.9 3.1 ...\n $ Petal.Length: num 1.4 1.4 1.3 1.5 1.4 1.7 1.4 1.5 1.4 1.5 ...\n $ Petal.Width : num 0.2 0.2 0.2 0.2 0.2 0.4 0.3 0.2 0.2 0.1 ...\n $ Species : Factor w/ 3 levels \"setosa\",\"versicolor\",..: 1 1 1 1 1 1 1 1 1 1 ...\n\nlibrary(dplyr)\n\nWarning: package 'dplyr' was built under R version 4.3.2\n\n\n\nAttaching package: 'dplyr'\n\n\nThe following objects are masked from 'package:stats':\n\n filter, lag\n\n\nThe following objects are masked from 'package:base':\n\n intersect, setdiff, setequal, union\n\nglimpse(iris)\n\nRows: 150\nColumns: 5\n$ Sepal.Length <dbl> 5.1, 4.9, 4.7, 4.6, 5.0, 5.4, 4.6, 5.0, 4.4, 4.9, 5.4, 4.…\n$ Sepal.Width <dbl> 3.5, 3.0, 3.2, 3.1, 3.6, 3.9, 3.4, 3.4, 2.9, 3.1, 3.7, 3.…\n$ Petal.Length <dbl> 1.4, 1.4, 1.3, 1.5, 1.4, 1.7, 1.4, 1.5, 1.4, 1.5, 1.5, 1.…\n$ Petal.Width <dbl> 0.2, 0.2, 0.2, 0.2, 0.2, 0.4, 0.3, 0.2, 0.2, 0.1, 0.2, 0.…\n$ Species <fct> setosa, setosa, setosa, setosa, setosa, setosa, setosa, s…\n\ncolnames(iris)\n\n[1] \"Sepal.Length\" \"Sepal.Width\" \"Petal.Length\" \"Petal.Width\" \"Species\" \n\ndim(iris)\n\n[1] 150 5\n\n# Create an empty vector to store means\nmean_iris <- NULL\n# Loop through columns of the dataset\nfor(i in seq_along(iris[,1])) {\n mean_iris <- c(mean_iris,mean(as.numeric(iris[i, 1:3])))\n}\n# Print the first 8 elements of myve\nprint(mean_iris[1:8])\n\n[1] 3.333333 3.100000 3.066667 3.066667 3.333333 3.666667 3.133333 3.300000\n\n\nQuestion:\n\nWhat is the differences between str() and glimpse()?\nAnd what is another function similar to them?"
},
{
"objectID": "Scripts/Script_4.html#nested-for-loops",
"href": "Scripts/Script_4.html#nested-for-loops",
"title": "Script_3",
"section": "Nested for loops",
"text": "Nested for loops\n\nn <- 5 # Define the size of the multiplication table (5x5)\n\n# Outer loop for rows \nfor (i in 1:n) {#iterates over each row index (i) from 1 to n.\n # Inner loop for columns\n for (j in 1:n) {#Inside the outer loop, iterates over each column index (j) from 1 to n.\n # Calculate product and print in a formatted way\n cat(sprintf(\"%2d \", i * j))\n }\n cat(\"\\n\") # Move to the next line after each row\n\n}\n\n 1 2 3 4 5 \n 2 4 6 8 10 \n 3 6 9 12 15 \n 4 8 12 16 20 \n 5 10 15 20 25 \n\n\n\n# Example: Nested for loops to create a multiplication table and save as a matrix\nn <- 5 # Define the size of the multiplication table (5x5)\n\n# Initialize an empty matrix to store results\nresult_matrix <- matrix(0, nrow = n, ncol = n)\n\n# Nested loops to calculate and store results\nfor (i in 1:n) {\n for (j in 1:n) {\n # Calculate product and store in matrix\n result_matrix[i, j] <- i * j\n }\n}\n\nWhat is the primary difference between the two nested for loop examples."
},
{
"objectID": "Scripts/Script_1.html",
"href": "Scripts/Script_1.html",
"title": "Script_1",
"section": "",
"text": "The simplest task you can perform with R”\n\ngetwd()\n\n[1] \"/home/hamed/Documents/Workshop_July2024/DAiR_2024.github.io-mainI/DAiR_2024/Scripts\"\n\n?setwd\n\n\n\nTo download and install packages from various repositories:\n\n# install.packages(\"tidyverse\")\n# install.packages(\"BiocManager\")\n# BiocManager::install(\"DESeq2\")\n# install.packages(\"devtools\")\n# devtools::install_github(\"keberwein/mlbgameday\")\n\nTo display the paths where R looks for installed packages:\n\n# .libPaths()\n\nTo display information about the first 10 packages installed in R:\n\n# installed.packages()[1:3]\n# head(installed.packages(), 3)\n\nDisplays the search path for loaded namespaces (packages) in your current R session:\n\nsearch()\n\n[1] \".GlobalEnv\" \"package:stats\" \"package:graphics\" \n[4] \"package:grDevices\" \"package:utils\" \"package:datasets\" \n[7] \"package:methods\" \"Autoloads\" \"package:base\" \n\n\n\nlibrary()#To load and attach packages for use in R \ndetach()#To detach (unload) packages\n\nTo uninstall (remove) packages from your R system:\n\n#remove.packages()#remove packages from the current library\n#uninstall.packages()#remove packages from the system.\n\n\n\n\nWe can store values in variables using the assignment operators <- and =, with <- being more prevalent in R coding conventions:\n\nx <- 10\ny <- \"Hello, world!\"\nz <- c(1, 2, 3)\nx\n\n[1] 10\n\ny\n\n[1] \"Hello, world!\"\n\nz\n\n[1] 1 2 3\n\n\nreassign z\n\nz <- log(x)\nz #Check the environment pane and look for `z` value.\n\n[1] 2.302585\n\n\n\nvariable names must follow specific rules:\n\nThey cannot start with a number.\n\n\n\nThey cannot contain spaces or special characters except for dot . and underscore _ which is called “snake_case” style.\nCertain words are reserved and cannot be used as variable names, such as TRUE, FALSE, NULL, if, else, function, etc.\n“Question for you: What are the reserved words in R?”\nR is case-sensitive, meaning VariableName and variablename would be considered different variables.\nYou can override the usual rules for variable naming in R by enclosing a name within backticks (`).\nYou should not use single or double quotes (’,“).\nQuestion for you: Why should we not use single or double quotes (’ or “)?\n\n\n\n# 1var <- 10 #Error: unexpected symbol in \"1var\"\n#if <- \"condition\" #Error: unexpected assignment in \"if <-\"\n\n\n`1var` <- 10\n`if` <- \"condition\"\n\nWe can perform operations such as multiplication and addition:\n\nx*5\n\n[1] 50\n\n(x+10)/2\n\n[1] 10\n\nx <- x+1\nx\n\n[1] 11\n\n\nThe order of operations in R:\n\n3 + 5 * 2 # This evaluates to 13 because multiplication is performed before addition\n\n[1] 13\n\n(3 + 5) * 2 # This evaluates to 16 because the parentheses change the order of operations\n\n[1] 16\n\n\nR handles nested operations by following the order of operations:\nexponents, multiplication, division, addition, and subtraction.\n\n(3 + (5 * (2 ^ 2)))\n\n[1] 23\n\n3 + 5 * 2 ^ 2 \n\n[1] 23\n\n3 + 5 * (2 ^ 2) \n\n[1] 23\n\n\nSmall decimal values\n\n2 / 10000 #scientific notation: 2e-4 is shorthand for 2 * 10^(-4)\n\n[1] 2e-04\n\n\n\n\n\nUse scientific notation for larger numbers\n\n6e8\n\n[1] 6e+08\n\n\nTrigonometric functions like sine:\n\nsin(1)\n\n[1] 0.841471\n\ncos(-90)\n\n[1] -0.4480736\n\n\nThe natural logarithm (base e):\n\nlog(20)\n\n[1] 2.995732\n\n\n\n\n\n\n3 == 5 # Evaluates to FALSE\n\n[1] FALSE\n\n# Not equal to\n3 != 5 # Evaluates to TRUE\n\n[1] TRUE\n\n# Greater than\n3 > 5 # Evaluates to FALSE\n\n[1] FALSE\n\n# Less than or equal to\n3 <= 5 # Evaluates to TRUE\n\n[1] TRUE\n\n\n\nIt’s generally recommended to use == for comparing integers:\n\n0.1 + 0.2\n\n[1] 0.3\n\n\nrefer to here the unexpected result is:\n0.30000000000000004\n\n# Comparing within a tolerance range\nx <- 0.1 + 0.2\ny <- 0.3\nx == y \n\n[1] FALSE\n\ntolerance <- 1e-8 # Example tolerance level\nabs(x - y) < tolerance # Evaluates to TRUE\n\n[1] TRUE\n\n\nComputers can represent decimal numbers with limited precision, so two numbers that appear identical when printed by R may have slightly different underlying representations due to this precision.\n\n\n\n\nOne important aspect to understand in R is its vectorized nature, where variables and functions can operate on entire vectors of values. For example:\n\nx1 <- c(1, 2, 3, 4, 5) # Creating a numeric vector\nx2 <- 1:5 # A numeric vector containing the values 1, 2, 3, 4, and 5\nx3 <- 2^x1\ny1 <- x * 2 # Multiplying each element of x by 2\ny2 <- 2^(1:5)#element is 2 raised to the power of each element in the sequence from 1 to 5\nz <- sqrt(x) # Taking the square root of each element of x\nx1\n\n[1] 1 2 3 4 5\n\nx2\n\n[1] 1 2 3 4 5\n\nx3\n\n[1] 2 4 8 16 32\n\ny1\n\n[1] 0.6\n\ny2\n\n[1] 2 4 8 16 32\n\nz\n\n[1] 0.5477226\n\n\n\n\n\nTo list the names of objects (variables, functions, etc.) that are currently stored in your workspace:\n\nls()\n\n [1] \"1var\" \"if\" \"tolerance\" \"x\" \"x1\" \"x2\" \n [7] \"x3\" \"y\" \"y1\" \"y2\" \"z\" \n\nls\n\nfunction (name, pos = -1L, envir = as.environment(pos), all.names = FALSE, \n pattern, sorted = TRUE) \n{\n if (!missing(name)) {\n pos <- tryCatch(name, error = function(e) e)\n if (inherits(pos, \"error\")) {\n name <- substitute(name)\n if (!is.character(name)) \n name <- deparse(name)\n warning(gettextf(\"%s converted to character string\", \n sQuote(name)), domain = NA)\n pos <- name\n }\n }\n all.names <- .Internal(ls(envir, all.names, sorted))\n if (!missing(pattern)) {\n if ((ll <- length(grep(\"[\", pattern, fixed = TRUE))) && \n ll != length(grep(\"]\", pattern, fixed = TRUE))) {\n if (pattern == \"[\") {\n pattern <- \"\\\\[\"\n warning(\"replaced regular expression pattern '[' by '\\\\\\\\['\")\n }\n else if (length(grep(\"[^\\\\\\\\]\\\\[<-\", pattern))) {\n pattern <- sub(\"\\\\[<-\", \"\\\\\\\\\\\\[<-\", pattern)\n warning(\"replaced '[<-' by '\\\\\\\\[<-' in regular expression pattern\")\n }\n }\n grep(pattern, all.names, value = TRUE)\n }\n else all.names\n}\n<bytecode: 0x5981b0b308a0>\n<environment: namespace:base>\n\n\nTo remove objects (variables, functions, etc.) from the workspace:\n\nrm(x2)\nls()\n\n [1] \"1var\" \"if\" \"tolerance\" \"x\" \"x1\" \"x3\" \n [7] \"y\" \"y1\" \"y2\" \"z\" \n\nrm(list = ls()) #removes all objects from the current workspace\nls()\n\ncharacter(0)"
},
{
"objectID": "Scripts/Script_1.html#package",
"href": "Scripts/Script_1.html#package",
"title": "Script_1",
"section": "",
"text": "To download and install packages from various repositories:\n\n# install.packages(\"tidyverse\")\n# install.packages(\"BiocManager\")\n# BiocManager::install(\"DESeq2\")\n# install.packages(\"devtools\")\n# devtools::install_github(\"keberwein/mlbgameday\")\n\nTo display the paths where R looks for installed packages:\n\n# .libPaths()\n\nTo display information about the first 10 packages installed in R:\n\n# installed.packages()[1:3]\n# head(installed.packages(), 3)\n\nDisplays the search path for loaded namespaces (packages) in your current R session:\n\nsearch()\n\n[1] \".GlobalEnv\" \"package:stats\" \"package:graphics\" \n[4] \"package:grDevices\" \"package:utils\" \"package:datasets\" \n[7] \"package:methods\" \"Autoloads\" \"package:base\" \n\n\n\nlibrary()#To load and attach packages for use in R \ndetach()#To detach (unload) packages\n\nTo uninstall (remove) packages from your R system:\n\n#remove.packages()#remove packages from the current library\n#uninstall.packages()#remove packages from the system."
},
{
"objectID": "Scripts/Script_1.html#assign-a-value-to-a-variable",
"href": "Scripts/Script_1.html#assign-a-value-to-a-variable",
"title": "Script_1",
"section": "",
"text": "We can store values in variables using the assignment operators <- and =, with <- being more prevalent in R coding conventions:\n\nx <- 10\ny <- \"Hello, world!\"\nz <- c(1, 2, 3)\nx\n\n[1] 10\n\ny\n\n[1] \"Hello, world!\"\n\nz\n\n[1] 1 2 3\n\n\nreassign z\n\nz <- log(x)\nz #Check the environment pane and look for `z` value.\n\n[1] 2.302585\n\n\n\nvariable names must follow specific rules:\n\nThey cannot start with a number.\n\n\n\nThey cannot contain spaces or special characters except for dot . and underscore _ which is called “snake_case” style.\nCertain words are reserved and cannot be used as variable names, such as TRUE, FALSE, NULL, if, else, function, etc.\n“Question for you: What are the reserved words in R?”\nR is case-sensitive, meaning VariableName and variablename would be considered different variables.\nYou can override the usual rules for variable naming in R by enclosing a name within backticks (`).\nYou should not use single or double quotes (’,“).\nQuestion for you: Why should we not use single or double quotes (’ or “)?\n\n\n\n# 1var <- 10 #Error: unexpected symbol in \"1var\"\n#if <- \"condition\" #Error: unexpected assignment in \"if <-\"\n\n\n`1var` <- 10\n`if` <- \"condition\"\n\nWe can perform operations such as multiplication and addition:\n\nx*5\n\n[1] 50\n\n(x+10)/2\n\n[1] 10\n\nx <- x+1\nx\n\n[1] 11\n\n\nThe order of operations in R:\n\n3 + 5 * 2 # This evaluates to 13 because multiplication is performed before addition\n\n[1] 13\n\n(3 + 5) * 2 # This evaluates to 16 because the parentheses change the order of operations\n\n[1] 16\n\n\nR handles nested operations by following the order of operations:\nexponents, multiplication, division, addition, and subtraction.\n\n(3 + (5 * (2 ^ 2)))\n\n[1] 23\n\n3 + 5 * 2 ^ 2 \n\n[1] 23\n\n3 + 5 * (2 ^ 2) \n\n[1] 23\n\n\nSmall decimal values\n\n2 / 10000 #scientific notation: 2e-4 is shorthand for 2 * 10^(-4)\n\n[1] 2e-04"
},
{
"objectID": "Scripts/Script_1.html#mathematical-functions",
"href": "Scripts/Script_1.html#mathematical-functions",
"title": "Script_1",
"section": "",
"text": "Use scientific notation for larger numbers\n\n6e8\n\n[1] 6e+08\n\n\nTrigonometric functions like sine:\n\nsin(1)\n\n[1] 0.841471\n\ncos(-90)\n\n[1] -0.4480736\n\n\nThe natural logarithm (base e):\n\nlog(20)\n\n[1] 2.995732"
},
{
"objectID": "Scripts/Script_1.html#relational-operators",
"href": "Scripts/Script_1.html#relational-operators",
"title": "Script_1",
"section": "",
"text": "3 == 5 # Evaluates to FALSE\n\n[1] FALSE\n\n# Not equal to\n3 != 5 # Evaluates to TRUE\n\n[1] TRUE\n\n# Greater than\n3 > 5 # Evaluates to FALSE\n\n[1] FALSE\n\n# Less than or equal to\n3 <= 5 # Evaluates to TRUE\n\n[1] TRUE\n\n\n\nIt’s generally recommended to use == for comparing integers:\n\n0.1 + 0.2\n\n[1] 0.3\n\n\nrefer to here the unexpected result is:\n0.30000000000000004\n\n# Comparing within a tolerance range\nx <- 0.1 + 0.2\ny <- 0.3\nx == y \n\n[1] FALSE\n\ntolerance <- 1e-8 # Example tolerance level\nabs(x - y) < tolerance # Evaluates to TRUE\n\n[1] TRUE\n\n\nComputers can represent decimal numbers with limited precision, so two numbers that appear identical when printed by R may have slightly different underlying representations due to this precision."
},
{
"objectID": "Scripts/Script_1.html#vector",
"href": "Scripts/Script_1.html#vector",
"title": "Script_1",
"section": "",
"text": "One important aspect to understand in R is its vectorized nature, where variables and functions can operate on entire vectors of values. For example:\n\nx1 <- c(1, 2, 3, 4, 5) # Creating a numeric vector\nx2 <- 1:5 # A numeric vector containing the values 1, 2, 3, 4, and 5\nx3 <- 2^x1\ny1 <- x * 2 # Multiplying each element of x by 2\ny2 <- 2^(1:5)#element is 2 raised to the power of each element in the sequence from 1 to 5\nz <- sqrt(x) # Taking the square root of each element of x\nx1\n\n[1] 1 2 3 4 5\n\nx2\n\n[1] 1 2 3 4 5\n\nx3\n\n[1] 2 4 8 16 32\n\ny1\n\n[1] 0.6\n\ny2\n\n[1] 2 4 8 16 32\n\nz\n\n[1] 0.5477226"
},
{
"objectID": "Scripts/Script_1.html#managing-environment",
"href": "Scripts/Script_1.html#managing-environment",
"title": "Script_1",
"section": "",
"text": "To list the names of objects (variables, functions, etc.) that are currently stored in your workspace:\n\nls()\n\n [1] \"1var\" \"if\" \"tolerance\" \"x\" \"x1\" \"x2\" \n [7] \"x3\" \"y\" \"y1\" \"y2\" \"z\" \n\nls\n\nfunction (name, pos = -1L, envir = as.environment(pos), all.names = FALSE, \n pattern, sorted = TRUE) \n{\n if (!missing(name)) {\n pos <- tryCatch(name, error = function(e) e)\n if (inherits(pos, \"error\")) {\n name <- substitute(name)\n if (!is.character(name)) \n name <- deparse(name)\n warning(gettextf(\"%s converted to character string\", \n sQuote(name)), domain = NA)\n pos <- name\n }\n }\n all.names <- .Internal(ls(envir, all.names, sorted))\n if (!missing(pattern)) {\n if ((ll <- length(grep(\"[\", pattern, fixed = TRUE))) && \n ll != length(grep(\"]\", pattern, fixed = TRUE))) {\n if (pattern == \"[\") {\n pattern <- \"\\\\[\"\n warning(\"replaced regular expression pattern '[' by '\\\\\\\\['\")\n }\n else if (length(grep(\"[^\\\\\\\\]\\\\[<-\", pattern))) {\n pattern <- sub(\"\\\\[<-\", \"\\\\\\\\\\\\[<-\", pattern)\n warning(\"replaced '[<-' by '\\\\\\\\[<-' in regular expression pattern\")\n }\n }\n grep(pattern, all.names, value = TRUE)\n }\n else all.names\n}\n<bytecode: 0x5981b0b308a0>\n<environment: namespace:base>\n\n\nTo remove objects (variables, functions, etc.) from the workspace:\n\nrm(x2)\nls()\n\n [1] \"1var\" \"if\" \"tolerance\" \"x\" \"x1\" \"x3\" \n [7] \"y\" \"y1\" \"y2\" \"z\" \n\nrm(list = ls()) #removes all objects from the current workspace\nls()\n\ncharacter(0)"
},
{
"objectID": "Scripts/Script_3.html#loops",
"href": "Scripts/Script_3.html#loops",
"title": "Script_3",
"section": "Loops",
"text": "Loops\n\nFor\nThis is an R Markdown document. Markdown is a simple formatting syntax for authoring HTML, PDF, and MS Word documents. For more details on using R Markdown see http://rmarkdown.rstudio.com.\nWhen you click the Knit button a document will be generated that includes both content as well as the output of any embedded R code chunks within the document. You can embed an R code chunk like this:\n\n# Define a vector\nx <- c(3, 5, 6, 144)\n\n# Loop through each element in the vector\nfor (i in x) {\n # Calculate the square of the current item\n y <- i * i\n # Print the square\n print(y)\n}\n\n[1] 9\n[1] 25\n[1] 36\n[1] 20736\n\n\n\nx[3]\n\n[1] 6\n\nfor (i in 1:length(x)){\n print(x[i])\n print(x[i]*x[i])\n}\n\n[1] 3\n[1] 9\n[1] 5\n[1] 25\n[1] 6\n[1] 36\n[1] 144\n[1] 20736"
},
{
"objectID": "Scripts/Script_3.html#including-plots",
"href": "Scripts/Script_3.html#including-plots",
"title": "Script_3",
"section": "Including Plots",
"text": "Including Plots\nYou can also embed plots, for example:\n\n\n\n\n\n\n\n\n\nNote that the echo = FALSE parameter was added to the code chunk to prevent printing of the R code that generated the plot."
},
{
"objectID": "Scripts/Script_2.html",
"href": "Scripts/Script_2.html",
"title": "Script_2",
"section": "",
"text": "This code\n\nx <- c(1, 2, 3)\n\nsnippet accomplishes two tasks:\n\nIt creates an object, specifically a vector of values, c(1, 2, 3).\nIt assigns that object to a name, x.\n\n\n\nIn other words, the name x is assigned a value (the object or vector c(1, 2, 3)) using the assignment operator <-, which is an arrow points in the opposite direction of the assignment.\n\ny <- x \nlobstr::obj_addr(x)\n\n[1] \"0x573b0a78c458\"\n\nlobstr::obj_addr(y)\n\n[1] \"0x573b0a78c458\"\n\n\n\nThis is an R Markdown document. Markdown is a simple formatting syntax for authoring HTML, PDF, and MS Word documents. For more details on using R Markdown see http://rmarkdown.rstudio.com.\nWhen you click the Knit button a document will be generated that includes both content as well as the output of any embedded R code chunks within the document. You can embed an R code chunk like this:\n\nsummary(cars)\n\n speed dist \n Min. : 4.0 Min. : 2.00 \n 1st Qu.:12.0 1st Qu.: 26.00 \n Median :15.0 Median : 36.00 \n Mean :15.4 Mean : 42.98 \n 3rd Qu.:19.0 3rd Qu.: 56.00 \n Max. :25.0 Max. :120.00 \n\n\n\n\n\nYou can also embed plots, for example:\n\n\n\n\n\n\n\n\n\nNote that the echo = FALSE parameter was added to the code chunk to prevent printing of the R code that generated the plot."
},
{
"objectID": "Scripts/Script_2.html#binding",
"href": "Scripts/Script_2.html#binding",
"title": "Script_2",
"section": "",
"text": "This code\n\nx <- c(1, 2, 3)\n\nsnippet accomplishes two tasks:\n\nIt creates an object, specifically a vector of values, c(1, 2, 3).\nIt assigns that object to a name, x.\n\n\n\nIn other words, the name x is assigned a value (the object or vector c(1, 2, 3)) using the assignment operator <-, which is an arrow points in the opposite direction of the assignment.\n\ny <- x \nlobstr::obj_addr(x)\n\n[1] \"0x573b0a78c458\"\n\nlobstr::obj_addr(y)\n\n[1] \"0x573b0a78c458\"\n\n\n\nThis is an R Markdown document. Markdown is a simple formatting syntax for authoring HTML, PDF, and MS Word documents. For more details on using R Markdown see http://rmarkdown.rstudio.com.\nWhen you click the Knit button a document will be generated that includes both content as well as the output of any embedded R code chunks within the document. You can embed an R code chunk like this:\n\nsummary(cars)\n\n speed dist \n Min. : 4.0 Min. : 2.00 \n 1st Qu.:12.0 1st Qu.: 26.00 \n Median :15.0 Median : 36.00 \n Mean :15.4 Mean : 42.98 \n 3rd Qu.:19.0 3rd Qu.: 56.00 \n Max. :25.0 Max. :120.00"
},
{
"objectID": "Scripts/Script_2.html#including-plots",
"href": "Scripts/Script_2.html#including-plots",
"title": "Script_2",
"section": "",
"text": "You can also embed plots, for example:\n\n\n\n\n\n\n\n\n\nNote that the echo = FALSE parameter was added to the code chunk to prevent printing of the R code that generated the plot."
},
{
"objectID": "data.html",
"href": "data.html",
"title": "DAiR_Workshop2024",
"section": "",
"text": "Author: Dr. Hamed Abdollahi \n PI: Dr. Homayoun Valafar"
},
{
"objectID": "data.html#sample-data-sets-of-workshop",
"href": "data.html#sample-data-sets-of-workshop",
"title": "DAiR_Workshop2024",
"section": "Sample Data sets of workshop",
"text": "Sample Data sets of workshop\n\n\n\n\n\n Download iris.csv\n \n \n Download Penguins.csv\n \n \n Download CO2.csv\n \n \n Download mtcars\n \n \n Download RNAseq\n \n \n \n \n Download titanic.xls\n \n \n \n Download 1996boys.xlsx\n \n Download 2015boys.xlsx\n \n \n Download caret_6.0\n \n \n Download tidymodels_1.2"
},
{
"objectID": "data.html#r-built-in-data-sets",
"href": "data.html#r-built-in-data-sets",
"title": "DAiR_Workshop2024",
"section": "R built-in data sets",
"text": "R built-in data sets\nR comes with several built-in data sets, which are generally used as demo data for playing with R functions.\nTo see the list of pre-loaded data:\n\nPlease enable JavaScript to experience the dynamic code cell content on this page.\n\nLoading a built-in R data\n\nPlease enable JavaScript to experience the dynamic code cell content on this page.\n\nPlease enable JavaScript to experience the dynamic code cell content on this page.\n\nPlease enable JavaScript to experience the dynamic code cell content on this page."
},
{
"objectID": "data.html#other-data-sets",
"href": "data.html#other-data-sets",
"title": "DAiR_Workshop2024",
"section": "Other Data sets",
"text": "Other Data sets\n\n\nDataset\n\n\n\n\nExamples of Other Datasets\n \n \n \n Type\n Package Name\n Author(s)\n CRAN\n Objective & GitHub\n Installatin\n \n \n \n \n Baseball\n mlbgameday\n Kris Eberwein\n Archived\n Data Collection\n install.packages(\"mlbgameday\") devtools::install_github(\"keberwein/mlbgameday\")\n \n \n Basketball\n ballr\n Ryan Elmore\n Archived\n Current and Historical Basketball Data\n install.packages(\"ballr\")devtools::install_github(\"rtelmore/ballr\")\n \n \n Hockey\n nhlapi\n Jozef Hajnala\n Active\n NHL API\n install.packages(\"nhlapi\")remotes::install_github(\"jozefhajnala/nhlapi\")\n \n \n Movie\n No Package\n IMDb\n NA\n Dataset(s) of movie information\n Download from the Hyperlink\n \n \n Movie\n No Package\n IMDb\n NA\n Dataset(s) of movie information\n Download from the Hyperlink"
},
{
"objectID": "Exercises/Exercise_2.html",
"href": "Exercises/Exercise_2.html",
"title": "Exercise_2",
"section": "",
"text": "Objective: You will practice installing R packages from CRAN using different methods and troubleshooting installation issues.\n\n\nInstall all the packages listed in the “Datasets” page of “DAiR_2024” under the “Import Data” section on the website.\nLoad the installed packages into your R session.\nVerify the installation and loading of these packages by printing their version numbers.\nProblem Statement:\nDownload and install the latest available versions of the caret package and tidymodels from CRAN. Perform the following tasks:\n\nAttempt to install the packages through the command line using R.\nIdentify any issues encountered during installation.\nCheck dependencies of the packages using the pkgnet library.\nAnalyze if there is any relationship between installation errors and the results from step 3.\nIf any issues arise, use the RStudio Console to install packages, specifying the install.packages arguments explicitly.\nFinally, attempt to install the packages using the Install tab in the Packages section of the Environment Pane in RStudio.\n\nHints:\n\nUse the install.packages() function in R to install packages from CRAN.\nMonitor the R console for any error messages during installation attempts.\nAdjust installation parameters such as dependencies, repos, or type as needed to troubleshoot installation issues.\nThe CRAN repository URL is “https://cran.r-project.org”.\nYou can specify type = \"source\" if needed.\n\nChallenge Question: What steps would you take if the installation fails due to dependency issues? How can you resolve these issues effectively?"
},
{
"objectID": "Scripts.html",
"href": "Scripts.html",
"title": "DAiR_Workshop2024",
"section": "",
"text": "Bioinformatics and Data Science Summer Workshops 2024\n\n\n\n \n \n \n \n \n \n \n Author: Dr. Hamed Abdollahi \n PI: Dr. Homayoun Valafar \n \n \n\n\n\n\n\n HowTo\n \n \n Primitives\n \n \n Random Numbers\n \n \n Data Wrangling\n \n \n Data Visualization Part 1\n \n \n Data Visualization Part 2\n \n \n \n Script_5.Rmd"
},
{
"objectID": "Exercises/Exercise_1.html#package-installation-and-troubleshooting",
"href": "Exercises/Exercise_1.html#package-installation-and-troubleshooting",
"title": "Exercise_1",
"section": "",
"text": "Objective: You will practice installing R packages from CRAN using different methods and troubleshooting installation issues.\n\n\nInstall all the packages listed in the “Datasets” page of “DAiR_2024” under the “Import Data” section on the website.\nLoad the installed packages into your R session.\nVerify the installation and loading of these packages by printing their version numbers.\nProblem Statement:\nDownload and install the latest available versions of the caret package and tidymodels from CRAN. Perform the following tasks:\n\nAttempt to install the packages through the command line using R.\nIdentify any issues encountered during installation.\nCheck dependencies of the packages using the pkgnet library.\nAnalyze if there is any relationship between installation errors and the results from step 3.\nIf any issues arise, use the RStudio Console to install packages, specifying the install.packages arguments explicitly.\nFinally, attempt to install the packages using the Install tab in the Packages section of the Environment Pane in RStudio.\n\nHints:\n\nUse the install.packages() function in R to install packages from CRAN.\nMonitor the R console for any error messages during installation attempts.\nAdjust installation parameters such as dependencies, repos, or type as needed to troubleshoot installation issues.\nThe CRAN repository URL is “https://cran.r-project.org”.\nYou can specify type = \"source\" if needed.\n\nChallenge Question: What steps would you take if the installation fails due to dependency issues? How can you resolve these issues effectively?"
},
{
"objectID": "Exercises/Exercise_3.html",
"href": "Exercises/Exercise_3.html",
"title": "Exercise_3",
"section": "",
"text": "#Objective: # wE will practice manipulating vectors and performing conditional calculations in R.\n#Problem Statement:\n# Create a vector containing numerical values and write a script that performs the following tasks:\nTask 1: Print out each element in a separate line. task 2: For each element: ### If the element is the 8th element of the vector, calculate its value multiplied by itself to the power of three (cubic multiplication). ## For all other elements, calculate its value multiplied by itself four times. ### Print the result of each calculation.\n#Hints: #Use a for loop to iterate through each element of the vector. #Use conditional statements (if-else) to differentiate between the 8th element and others."
},
{
"objectID": "Exercises/Exercise_3.html#vector-manipulation-and-conditional-calculation",
"href": "Exercises/Exercise_3.html#vector-manipulation-and-conditional-calculation",
"title": "Exercise_3",
"section": "",
"text": "#Objective: # wE will practice manipulating vectors and performing conditional calculations in R.\n#Problem Statement:\n# Create a vector containing numerical values and write a script that performs the following tasks:\nTask 1: Print out each element in a separate line. task 2: For each element: ### If the element is the 8th element of the vector, calculate its value multiplied by itself to the power of three (cubic multiplication). ## For all other elements, calculate its value multiplied by itself four times. ### Print the result of each calculation.\n#Hints: #Use a for loop to iterate through each element of the vector. #Use conditional statements (if-else) to differentiate between the 8th element and others."
},
{
"objectID": "Exercises/Exercise_1.html#scripting-commands-in-r",
"href": "Exercises/Exercise_1.html#scripting-commands-in-r",
"title": "Exercise_1",
"section": "",
"text": "Objective: We will practice scripting commands in R, including file creation, editing, sourcing scripts, and using sink() to capture and redirect output.\nProblem Statement:\nPerform the following tasks in R:\n\nCreate a script file named command_example.R.\nEdit the script file using file.edit() to add the following content:\nCopy & paste code from here.\nExecute the script file command_example.R and print the results.\nRedirect the output of the script to a text file named result_command_example.txt.\nStop redirecting output.\n\nHints:\n\nUse file.create() to create the script file.\nUse file.edit() to modify the script file with the provided content.\nUse source(\"\") to execute the script and display its output in the console.\nUse sink(\"file_name.txt\") to redirect R output to a text file.\nUse sink() without arguments to stop redirecting output.\n\nChallenge Question: How would you modify the script to handle errors or warnings that might occur during script execution? What methods can you use to capture and handle such messages effectively?\nThis exercise will help students practice fundamental scripting tasks in R, including file handling, sourcing scripts, and managing script output using sink(), preparing them for more complex data processing and automation tasks in R."
},
{
"objectID": "Exercises/Exercise_2.html#package-installation-and-troubleshooting",
"href": "Exercises/Exercise_2.html#package-installation-and-troubleshooting",
"title": "Exercise_2",
"section": "",
"text": "Objective: You will practice installing R packages from CRAN using different methods and troubleshooting installation issues.\n\n\nInstall all the packages listed in the “Datasets” page of “DAiR_2024” under the “Import Data” section on the website.\nLoad the installed packages into your R session.\nVerify the installation and loading of these packages by printing their version numbers.\nProblem Statement:\nDownload and install the latest available versions of the caret package and tidymodels from CRAN. Perform the following tasks:\n\nAttempt to install the packages through the command line using R.\nIdentify any issues encountered during installation.\nCheck dependencies of the packages using the pkgnet library.\nAnalyze if there is any relationship between installation errors and the results from step 3.\nIf any issues arise, use the RStudio Console to install packages, specifying the install.packages arguments explicitly.\nFinally, attempt to install the packages using the Install tab in the Packages section of the Environment Pane in RStudio.\n\nHints:\n\nUse the install.packages() function in R to install packages from CRAN.\nMonitor the R console for any error messages during installation attempts.\nAdjust installation parameters such as dependencies, repos, or type as needed to troubleshoot installation issues.\nThe CRAN repository URL is “https://cran.r-project.org”.\nYou can specify type = \"source\" if needed.\n\nChallenge Question: What steps would you take if the installation fails due to dependency issues? How can you resolve these issues effectively?"
},
{
"objectID": "index.html#functions-wickham2019advanced",
"href": "index.html#functions-wickham2019advanced",
"title": "DAiR Workshop 2024",
"section": "Functions Wickham (2019)",
"text": "Functions Wickham (2019)\nTo comprehend functions in R thoroughly, it’s essential to grasp two key concepts:\n\nFunction Components: Functions consist of three primary components:\n\nFormals (formals()):\n\nThis represents the list of arguments defined when the function is created. Arguments determine how you call and pass data into the function. They are inputs provided to the function.\n\nBody (body()):\n\nThe body contains the actual code that executes when the function is called. It defines what the function does with the provided arguments. The sequence of expressions that define what the function does.\n\nEnvironment (environment()):\n\nThe environment specifies the context or scope in which the function operates. It dictates how the function accesses and interacts with data and other objects.\n\n\n\nThe environment is implicitly determined based on where the function is defined. If the function is defined within the global environment, it inherits that environment unless specified otherwise..\n\n\nPrimitive Base Functions: Despite the general rule that functions are defined in R, there are exceptions. A subset of functions known as “primitive” base functions is implemented directly in C for efficiency reasons.\n\nSuch as sum() as type builtin and [ as type special,which are exceptions to the standard function structure.\nThey directly call C code for execution and offering optimized performance for basic operations like summing elements or extracting subsets of data.\nHence, when you check their attributes using formals(), body(), or environment() functions, they typically return NULL because these attributes are not applicable to primitive functions\nPrimitive functions in R are typically found in the base package of R.\n\nFunctions as Objects: Similar to vectors and other data types, functions are objects in R.\n\nR does not require special syntax for defining and naming functions.\n\n\nPlease enable JavaScript to experience the dynamic code cell content on this page.\n\nYou create a function object using the function keyword and then bind it to a name using the assignment operator <-.\nThis flexibility allows for dynamic and powerful programming capabilities within R.\nsrcref is useful for printing or displaying the original source code that was used to create the function.\nAnonymous functions, also known as lambda functions, e useful in situations where you need a function for a short period or when it’s not necessary to assign a name.\n\n\nPlease enable JavaScript to experience the dynamic code cell content on this page.\n\n\nThis example demonstrate the use of function lapply along with anonymous functions defined using function(x).\n\n\nPlease enable JavaScript to experience the dynamic code cell content on this page.\n\n\nPutting functions in a list can be very useful, especially when you need to store multiple functions together for organizational purposes or to pass them as arguments to other functions.\n\n```{webr}\n# Define some example functions\nsquare <- function(x) x^2\ncube <- function(x) x^3\nsqrt <- function(x) x^0.5\n\n# Create a list of functions\nfunction_list <- list(\n square = square,\n cube = cube,\n sqrt = sqrt\n)\n\n# Access and use functions from the list\nfunction_list$square(5)\nfunction_list$cube(4)\nfunction_list$sqrt(16)\n```\n\nIn the above example:\n\nWe define three functions (square, cube, and sqrt).\nWe create a list function_list containing these functions, where each function is assigned a name within the list (square, cube, sqrt).\nWe then call each function from the list using $ notation (function_list$square, function_list$cube, function_list$sqrt).\n\n\n\n\nIf we have the arguments for a function already stored in a data structure, such as a list or a vector, we can still call the function using the do.call() function in R.\n\n\nPlease enable JavaScript to experience the dynamic code cell content on this page.\n\n\nUnderstanding these aspects is fundamental for mastering function usage and manipulation in R.\nBase R provides two ways to compose multiple function calls: nesting and piping.\n\nNesting\nIt is straightforward but can become unwieldy with complex chains of functions.\n\n\nPlease enable JavaScript to experience the dynamic code cell content on this page.\n\nIn this example:\n\nmean(data) computes the mean of the data.\ndata - mean(data) computes the deviations from the mean.\n(data - mean(data))^2 squares the deviations.\nmean((data - mean(data))^2) computes the mean of the squared deviations (variance).\nsqrt(mean((data - mean(data))^2)) takes the square root of the variance to get the standard deviation.\n\nPiping\nOffers improved readability and maintainability by breaking down complex operations into a sequence of simple steps.\n\nintroduced in the magrittr package and later incorporated into dplyr.\nThe pipe operator %>% passes the result of one function call as the first argument to the next function.\n\n\nPlease enable JavaScript to experience the dynamic code cell content on this page.\n\nIn this example:\n\ndata %>% starts the pipeline with the data.\n-(mean(.)) subtracts the mean of data from each element.\n^(2) squares each deviation.\nmean() computes the mean of the squared deviations.\nsqrt() takes the square root of the variance to get the standard deviation.\n\n\n\n\n\nFunctions (or more precisely, function closures) have three basic components:\n\nA formal argument list\n\nA comma-separated list of arguments\nThe ... argument is special and generally used if the number of arguments is unknown or in cases where the arguments will be passed on to another function.\n\nA body\n\nIt is usually a collection of statements in braces\n\nAn environment\n\nThe environment that was active at the time that the function was created.\nAny symbols bound in that environment are captured and available to the function.\nThe combination of the code of the function and the bindings in its environment is called a ‘function closure’, a term from functional programming theory.\n\n\nPlease enable JavaScript to experience the dynamic code cell content on this page.\n\n\n\nPlease enable JavaScript to experience the dynamic code cell content on this page.\n\n\n\n\n\n\n\n\n\n\n\nFunction\nDescription\n\n\n\n\nabs(x)\nComputes the absolute value |x|.\n\n\nsqrt(x)\nComputes the square root of x.\n\n\nlog(x)\nComputes the logarithm of x with the natural number e as the base.\n\n\nlog(x, base = a)\nComputes the logarithm of x with the number a as the base.\n\n\na^x\nComputes a^x.\n\n\nexp(x)\nComputes e^x.\n\n\nsin(x)\nComputes sin(x).\n\n\nsum(x)\nWhen x is a vector x = (x1, x2, x3, ..., xn), computes the sum of the elements of x: sum(x) = sum(i=1 to n) xi.\n\n\nprod(x)\nWhen x is a vector x = (x1, x2, x3, ..., xn), computes the product of the elements of x: prod(x) = prod(i=1 to n) xi.\n\n\npi\nA built-in variable with value π, the ratio of the circumference of a circle to its diameter.\n\n\nx %% a\nComputes x modulo a.\n\n\nfactorial(x)\nComputes x!.\n\n\nchoose(n, k)\nComputes n choose k (binomial coefficient).",
"crumbs": [
"Home",
"DAiR Workshop 2024"
]
},
{
"objectID": "index.html#syntax-rules-in-r",
"href": "index.html#syntax-rules-in-r",
"title": "DAiR Workshop 2024",
"section": "Syntax Rules in R",
"text": "Syntax Rules in R\n\nCase Sensitivity: R is case sensitive, meaning that variable and Variable would be treated as two different variables.\nWhite Space: R ignores white space, allowing for flexible code formatting.\nVariable Names:\n\nMust start with a letter (A-Z or a-z).\nCan include letters, digits (0-9), dots (.), and underscores (_).\n\nComments: Can be inserted using a hash # symbol. Anything after # on a line is considered a comment and is not executed.\nFunctions: Must be written with parentheses, even if there is nothing within them. For example: ls().",
"crumbs": [
"Home",
"DAiR Workshop 2024"
]
},
{
"objectID": "index.html#data-types-in-r",
"href": "index.html#data-types-in-r",
"title": "DAiR Workshop 2024",
"section": "Data Types in R",
"text": "Data Types in R\n\nVector\n\nVectors are single-dimensional, homogeneous data structures.\nSo, Vectors can only contain elements of one type!\nTo create a vector, concatenating values using the c() function.\n\n\n\nThis build of rgl does not include OpenGL functions. Use\n rglwidget() to display results, e.g. via options(rgl.printRglwidget = TRUE).\n\n\nnull \n 1 \n\n\n\n\n\n\n\nVectors must have their values all of the same mode.\n\n\nPlease enable JavaScript to experience the dynamic code cell content on this page.\n\n\n\n\nIn vectors, cells are accessible through indexing operations.\nSome important functions are: c() , vctor(),length(), class(), typeof(), attributes(), is.double(), is.numeric(), is.integer(), is.logical(), is.character(), is.vector() .\n\n\nPlease enable JavaScript to experience the dynamic code cell content on this page.\n\nA vector can be empty and still have a mode.\n\nFor example, an empty character string vector is represented as character(0), while an empty numeric vector is represented as numeric(0).\n\n\nPlease enable JavaScript to experience the dynamic code cell content on this page.\n\n\nNumeric sequences:\n\nRegular sequences can be created using the function seq() and its shortcuts seq.int(), seq_along(), and seq_len().\nnumeric or integer values between two well defined points (from and to) with an equidistant spacing.\n\nPlease enable JavaScript to experience the dynamic code cell content on this page.\n\nCharacter Sequences:\n\nNeed the letters of the alphabet use LETTERS and letters\n\nFactors\n\nType of vector in R used to represent categorical data where the levels of the factor represent distinct groups or categories.\n\n\nPlease enable JavaScript to experience the dynamic code cell content on this page.\n\n\n\nPlease enable JavaScript to experience the dynamic code cell content on this page.\n\n\nThe tapply() function in R is used to apply a function (such as mean(), sum(), median(), etc.) to subsets of data defined by factors or groupings. It allows you to compute a statistic for each group defined by levels of a factor, treating them as separate entities.\n Let’s start Exercise_4!\n\n\n\n\n In our previous session, we successfully covered these key tasks:\n We delved into creating projects and utilizing the icons on the toolbar to streamline our workflow.\n We learned how to check for package issues using the rcmdcheck package, ensuring our packages function correctly.\n We discussed various AI-APIs and packages related to R, exploring their applications and integrations.\n We practiced retrieving data from the PDB API, gaining hands-on experience in fetching and handling external data sources.\n We had a brief introduction to OOP concepts and how they apply within the R programming language.\n We discussed the structure and architecture of R, focusing on classes and objects, understanding how R is built and how it operates.\n\n We became familiar with attributes and methods in R, as well as the vector data type.\n\n\nTypes of Factors:\n\nOrdered Factors: These are used when the levels have a natural ordering or hierarchy (e.g., low, medium, high). ordered() function creates such ordered factors\n\n\n\nUnordered Factors: These are used when the levels do not have a specific order (e.g., categories like red, green, blue).\n\n\nPlease enable JavaScript to experience the dynamic code cell content on this page.\n\n\nPlease enable JavaScript to experience the dynamic code cell content on this page.\n\nImportance of factors:\n\nData Integrity: Factors ensure that categorical data remains distinct and well-defined throughout data manipulations and analyses.\n\n\n\nStatistical Modeling: Factors are crucial in statistical modeling and analyses, where they play a key role in regression models, ANOVA (Analysis of Variance), and other statistical tests by correctly interpreting categorical predictors and grouping variables.\n\n\nReplicating elements\n\nReplicate one specific value n times.\nGiven an existing vector: Replicate each element n times.\nGiven an existing vector: Replicate the entire vector n times.\nGiven an existing vector: Replicate the elements different amount of times.\n\nPlease enable JavaScript to experience the dynamic code cell content on this page.\nhe function rep.int() in R is used to replicate elements of a vector or a list.\n\n\nPlease enable JavaScript to experience the dynamic code cell content on this page.\n\nTo find the sample size (number of observations) in R using the length() :\n\n\nPlease enable JavaScript to experience the dynamic code cell content on this page.\n\n\nIf we combine elements of different types, R has to convert all elements into the same type/class as vectors can only contain elements of one type.\nThis is called ‘coercion’. So, In R, coercion occurs when elements of different types are combined in a vector:\n\n\nImplicit coercion: R chooses the best option.\n\n\nPlease enable JavaScript to experience the dynamic code cell content on this page.\n\nEvery numeric value equal to 0/0L converted to logical results in FALSE.\nEvery numeric value not equal to 0/0L converted to logical results in TRUE.\nEvery TRUE converted to numeric will be 1 (or 1L).\nEvery FALSE converted to numeric will be 0 (or 0L).\n\nPlease enable JavaScript to experience the dynamic code cell content on this page.\nExplicit coercion: we force something to be of a different type:\nas.integer() , as.numeric() ,as.character() ,as.logical() ,as.matrix().\n\nPlease enable JavaScript to experience the dynamic code cell content on this page.\nIf R is not able to convert elements, it will return NA\n\nPlease enable JavaScript to experience the dynamic code cell content on this page.\n\nMultiply a sequence with a scalar (a single number)\n\nPlease enable JavaScript to experience the dynamic code cell content on this page.\nHow R handles vector arithmetic:\n\nPlease enable JavaScript to experience the dynamic code cell content on this page.\n\nNegative Indices: Negative indices can be used to exclude specific elements.\nLogical Indices: Logical vectors can also be used for indexing, selecting elements based on conditions.(Select elements based on logical conditions TRUE or FALSE)\n\n\nPlease enable JavaScript to experience the dynamic code cell content on this page.\n\n\n\n\n\nMatrices\n\nA matrix is a two-dimensional data structure where elements are organized into rows and columns.\nIt is homogeneous, meaning all elements within a matrix must be of the same data type (e.g., numeric, character, logical).\n\n\n\nnull \n 3 \n\n\n\n\n\n\n\nIf different data types are attempted to be combined into a matrix using matrix(), R will coerce them into a common type that can accommodate all elements.\nMatrices are created using the matrix() function, which takes vectors as input and arranges them into a specified number of rows and columns.\n\n\nPlease enable JavaScript to experience the dynamic code cell content on this page.\n\n\n\nPlease enable JavaScript to experience the dynamic code cell content on this page.\n\n\nThe %o% operator in R is used to compute the outer product of two vectors.\n\n\nPlease enable JavaScript to experience the dynamic code cell content on this page.\n\nThe outer product ab will be a matrix where each element ab[i,j] is a[i]×b[j].\n\nMatrix Transpose (t()):\n\nThe t() function computes the transpose of a matrix. It swaps rows with columns.\n\n\nPlease enable JavaScript to experience the dynamic code cell content on this page.\n\n\n\n\n\nArrays\n\nAn array is a multiply subscripted collection of data entries, typically of the same data type, such as numeric values.\nArrays are generalizations of matrices and can have multiple dimensions. A way to store and manipulate multi-dimensional data beyond the two dimensions provided by matrices.\nArrays can have multiple dimensions.\nDimensions in R arrays are indexed from one up to the values given in the dimension vector. This means the first dimension of an array is indexed by 1, the second by 2, and so on.\n\n\n\nnull \n 5 \n\n\n\n\n\n\n\n\nPlease enable JavaScript to experience the dynamic code cell content on this page.\n\nUsing Vectors as Arrays:\nIn R, a vector can be treated as an array if it has a dim attribute set. This allows you to reshape a vector into a multi-dimensional array using the dim() function or directly assigning the dim attribute.\n\n\nPlease enable JavaScript to experience the dynamic code cell content on this page.\n\n\nWhen working with arrays and matrices:\n\nConcatenation with c(): The c() function in R concatenates its arguments to create a single vector. However, when used with arrays or matrices, c() disregards any dimension attributes (dim and dimnames). This means it treats the input as a flat sequence of elements and does not respect the structure of arrays or matrices.\n\n\n\nDifference from cbind() and rbind(): Unlike cbind() (column bind) and rbind() (row bind), which respect the dim attributes of matrices and arrays, c() does not preserve these attributes. This behavior can be useful when you specifically want to flatten an array or matrix into a vector format.\nCoercion to Vector: To convert an array or matrix back to a simple vector while preserving its structure, the recommended approach is to use as.vector(). For example:\n\n\nPlease enable JavaScript to experience the dynamic code cell content on this page.\n\nThis function maintains the structure of the object, ensuring that it remains a vector but retains any dimension attributes.\nc\n\n\n\n\nLists\n\nLists can contain objects of different types and structures.\nLists have elements, each of which can contain any type of R object.\nThere is no particular need for the components to be of the same mode or type, or example, a list could consist of a numeric vector, a logical value, a matrix, a complex vector, a character array, a function, and so on.\n\n\nPlease enable JavaScript to experience the dynamic code cell content on this page.\n\nIf Lst is the name of a list with four components, these may be individually referred to as Lst[[1]], Lst[[2]], Lst[[3]] and Lst[[4]].\nIf, further, Lst[[4]] is a vector subscripted array then Lst[[4]][1] is its first entry.\n\n\n\nPlease enable JavaScript to experience the dynamic code cell content on this page.\n\n\nNew lists may be formed from existing objects by the function list().\n\n\n\nData Frames\n\nData frames are indeed structured as lists with class “data.frame”.\nData frames are widely used in R for storing and manipulating structured data,\nData frames have specific rules regarding their composition and structure:\n\nComponents of Data Frames: Data frames can include components that are vectors (numeric, character, or logical), factors, numeric matrices, lists, or other data frames.\n\n\n\nVariables in Data Frames: Matrices, lists, and data frames contribute variables (columns) to the new data frame based on their columns, elements, or variables, respectively.\nConsistent Length and Size: Variables (columns) within a data frame must have consistent lengths for vectors and consistent row counts for matrices. This ensures uniformity across columns in terms of data structure.\nMatrix-Like Operations: While data frames are list-like structures, they can be treated like matrices in many operations. They can be displayed in matrix form, and their rows and columns can be accessed using matrix indexing conventions.\n\n\n\n\nnull \n 7 \n\n\n\n\n\n\n\n\nPlease enable JavaScript to experience the dynamic code cell content on this page.\n\n\n\nPlease enable JavaScript to experience the dynamic code cell content on this page.\n\n\nLanguage objects can be converted to and from lists by the as.list and as.call functions.\nSymbols can be created through the functions as.name and quote.\nThe main difference between language object and expression object is that an expression object can contain several such expressions.\n\n\n\nMissing values\n\nMissing values in R still have a class.(missing numeric, integer, logical, or character missing values.)\nNaN: Mathematically not defined (and always of class numeric).\n\nPlease enable JavaScript to experience the dynamic code cell content on this page.\nNA: Missing value, NA’s still have classes!\nNaN is also NA but not vice versa.",
"crumbs": [
"Home",
"DAiR Workshop 2024"
]
},
{
"objectID": "datatype.html",
"href": "datatype.html",
"title": "DAiR Workshop 2024",
"section": "",
"text": "Author: Dr. Hamed Abdollahi \n PI: Dr. Homayoun Valafar",
"crumbs": [
"Home",
"Data Type in R"
]
},
{
"objectID": "datatype.html#data-types-in-r",
"href": "datatype.html#data-types-in-r",
"title": "DAiR Workshop 2024",
"section": "Data Types in R",
"text": "Data Types in R\n\nVector\n\nVectors are single-dimensional, homogeneous data structures.\nSo, Vectors can only contain elements of one type!\nTo create a vector, concatenating values using the c() function.\n\n\n\nThis build of rgl does not include OpenGL functions. Use\n rglwidget() to display results, e.g. via options(rgl.printRglwidget = TRUE).\n\n\nnull \n 1 \n\n\n\n\n\n\n\nVectors must have their values all of the same mode.\n\n\nPlease enable JavaScript to experience the dynamic code cell content on this page.\n\n\n\n\nIn vectors, cells are accessible through indexing operations.\nSome important functions are: c() , vctor(),length(), class(), typeof(), attributes(), is.double(), is.numeric(), is.integer(), is.logical(), is.character(), is.vector() .\n\n\nPlease enable JavaScript to experience the dynamic code cell content on this page.\n\nA vector can be empty and still have a mode.\n\nFor example, an empty character string vector is represented as character(0), while an empty numeric vector is represented as numeric(0).\n\n\nPlease enable JavaScript to experience the dynamic code cell content on this page.\n\n\nNumeric sequences:\n\nRegular sequences can be created using the function seq() and its shortcuts seq.int(), seq_along(), and seq_len().\nnumeric or integer values between two well defined points (from and to) with an equidistant spacing.\n\nPlease enable JavaScript to experience the dynamic code cell content on this page.\n\nCharacter Sequences:\n\nNeed the letters of the alphabet use LETTERS and letters\n\nFactors\n\nType of vector in R used to represent categorical data where the levels of the factor represent distinct groups or categories.\n\n\nPlease enable JavaScript to experience the dynamic code cell content on this page.\n\n\n\nPlease enable JavaScript to experience the dynamic code cell content on this page.\n\n\nThe tapply() function in R is used to apply a function (such as mean(), sum(), median(), etc.) to subsets of data defined by factors or groupings. It allows you to compute a statistic for each group defined by levels of a factor, treating them as separate entities.\n Let’s start Exercise_4!\n\n\n\n\n In our previous session, we successfully covered these key tasks:\n We delved into creating projects and utilizing the icons on the toolbar to streamline our workflow.\n We learned how to check for package issues using the rcmdcheck package, ensuring our packages function correctly.\n We discussed various AI-APIs and packages related to R, exploring their applications and integrations.\n We practiced retrieving data from the PDB API, gaining hands-on experience in fetching and handling external data sources.\n We had a brief introduction to OOP concepts and how they apply within the R programming language.\n We discussed the structure and architecture of R, focusing on classes and objects, understanding how R is built and how it operates.\n\n We became familiar with attributes and methods in R, as well as the vector data type.\n\n\nTypes of Factors:\n\nOrdered Factors: These are used when the levels have a natural ordering or hierarchy (e.g., low, medium, high). ordered() function creates such ordered factors\n\n\n\nUnordered Factors: These are used when the levels do not have a specific order (e.g., categories like red, green, blue).\n\n\nPlease enable JavaScript to experience the dynamic code cell content on this page.\n\n\nPlease enable JavaScript to experience the dynamic code cell content on this page.\n\nImportance of factors:\n\nData Integrity: Factors ensure that categorical data remains distinct and well-defined throughout data manipulations and analyses.\n\n\n\nStatistical Modeling: Factors are crucial in statistical modeling and analyses, where they play a key role in regression models, ANOVA (Analysis of Variance), and other statistical tests by correctly interpreting categorical predictors and grouping variables.\n\n\nReplicating elements\n\nReplicate one specific value n times.\nGiven an existing vector: Replicate each element n times.\nGiven an existing vector: Replicate the entire vector n times.\nGiven an existing vector: Replicate the elements different amount of times.\n\nPlease enable JavaScript to experience the dynamic code cell content on this page.\nhe function rep.int() in R is used to replicate elements of a vector or a list.\n\n\nPlease enable JavaScript to experience the dynamic code cell content on this page.\n\nTo find the sample size (number of observations) in R using the length() :\n\n\nPlease enable JavaScript to experience the dynamic code cell content on this page.\n\n\nIf we combine elements of different types, R has to convert all elements into the same type/class as vectors can only contain elements of one type.\nThis is called ‘coercion’. So, In R, coercion occurs when elements of different types are combined in a vector:\n\n\nImplicit coercion: R chooses the best option.\n\n\nPlease enable JavaScript to experience the dynamic code cell content on this page.\n\nEvery numeric value equal to 0/0L converted to logical results in FALSE.\nEvery numeric value not equal to 0/0L converted to logical results in TRUE.\nEvery TRUE converted to numeric will be 1 (or 1L).\nEvery FALSE converted to numeric will be 0 (or 0L).\n\nPlease enable JavaScript to experience the dynamic code cell content on this page.\nExplicit coercion: we force something to be of a different type:\nas.integer() , as.numeric() ,as.character() ,as.logical() ,as.matrix().\n\nPlease enable JavaScript to experience the dynamic code cell content on this page.\nIf R is not able to convert elements, it will return NA\n\nPlease enable JavaScript to experience the dynamic code cell content on this page.\n\nMultiply a sequence with a scalar (a single number)\n\nPlease enable JavaScript to experience the dynamic code cell content on this page.\nHow R handles vector arithmetic:\n\nPlease enable JavaScript to experience the dynamic code cell content on this page.\n\nNegative Indices: Negative indices can be used to exclude specific elements.\nLogical Indices: Logical vectors can also be used for indexing, selecting elements based on conditions.(Select elements based on logical conditions TRUE or FALSE)\n\n\nPlease enable JavaScript to experience the dynamic code cell content on this page.\n\n\n\n\n\nMatrices\n\nA matrix is a two-dimensional data structure where elements are organized into rows and columns.\nIt is homogeneous, meaning all elements within a matrix must be of the same data type (e.g., numeric, character, logical).\n\n\n\nnull \n 3 \n\n\n\n\n\n\n\nIf different data types are attempted to be combined into a matrix using matrix(), R will coerce them into a common type that can accommodate all elements.\nMatrices are created using the matrix() function, which takes vectors as input and arranges them into a specified number of rows and columns.\n\n\nPlease enable JavaScript to experience the dynamic code cell content on this page.\n\n\nThe %o% operator in R is used to compute the outer product of two vectors.\n\n\nPlease enable JavaScript to experience the dynamic code cell content on this page.\n\nThe outer product ab will be a matrix where each element ab[i,j] is a[i]×b[j].\n\nMatrix Transpose (t()):\n\nThe t() function computes the transpose of a matrix. It swaps rows with columns.\n\n\nPlease enable JavaScript to experience the dynamic code cell content on this page.\n\n\n\n\n\nArrays\n\nAn array is a multiply subscripted collection of data entries, typically of the same data type, such as numeric values.\nArrays are generalizations of matrices and can have multiple dimensions. A way to store and manipulate multi-dimensional data beyond the two dimensions provided by matrices.\nArrays can have multiple dimensions.\nDimensions in R arrays are indexed from one up to the values given in the dimension vector. This means the first dimension of an array is indexed by 1, the second by 2, and so on.\n\n\n\nnull \n 5 \n\n\n\n\n\n\n\n\nPlease enable JavaScript to experience the dynamic code cell content on this page.\n\nUsing Vectors as Arrays:\nIn R, a vector can be treated as an array if it has a dim attribute set. This allows you to reshape a vector into a multi-dimensional array using the dim() function or directly assigning the dim attribute.\n\n\nPlease enable JavaScript to experience the dynamic code cell content on this page.\n\n\nWhen working with arrays and matrices:\n\nConcatenation with c(): The c() function in R concatenates its arguments to create a single vector. However, when used with arrays or matrices, c() disregards any dimension attributes (dim and dimnames). This means it treats the input as a flat sequence of elements and does not respect the structure of arrays or matrices.\n\n\n\nDifference from cbind() and rbind(): Unlike cbind() (column bind) and rbind() (row bind), which respect the dim attributes of matrices and arrays, c() does not preserve these attributes. This behavior can be useful when you specifically want to flatten an array or matrix into a vector format.\nCoercion to Vector: To convert an array or matrix back to a simple vector while preserving its structure, the recommended approach is to use as.vector(). For example:\n\n\nPlease enable JavaScript to experience the dynamic code cell content on this page.\n\nThis function maintains the structure of the object, ensuring that it remains a vector but retains any dimension attributes.\nc\n\n\n\n\nLists\n\nLists can contain objects of different types and structures.\nLists have elements, each of which can contain any type of R object.\n\n\nWarning in brewer.pal(n = 16, name = \"Dark2\"): n too large, allowed maximum for palette Dark2 is 8\nReturning the palette you asked for with that many colors\n\n\nnull \n 7 \n\n\n\n\n\n\nThere is no particular need for the components to be of the same mode or type, or example, a list could consist of a numeric vector, a logical value, a matrix, a complex vector, a character array, a function, and so on.\n\n\nPlease enable JavaScript to experience the dynamic code cell content on this page.\n\nIf Lst is the name of a list with four components, these may be individually referred to as Lst[[1]], Lst[[2]], Lst[[3]] and Lst[[4]].\nIf, further, Lst[[4]] is a vector subscripted array then Lst[[4]][1] is its first entry.\n\n\n\nPlease enable JavaScript to experience the dynamic code cell content on this page.\n\n\nNew lists may be formed from existing objects by the function list().\n\n\n\nData Frames\n\nThe basis for most data analyses in R are data frames.\nData frames are indeed structured as lists with class “data.frame”.\nData frames are widely used in R for storing and manipulating structured data,\nData frames have specific rules regarding their composition and structure:\n\nComponents of Data Frames: Data frames can include components that are vectors (numeric, character, or logical), factors, numeric matrices, lists, or other data frames.\n\n\n\nVariables in Data Frames: Matrices, lists, and data frames contribute variables (columns) to the new data frame based on their columns, elements, or variables, respectively.\nEach column represents a variable (e.g., age) and each row represents an observation (e.g., an individual).\nConsistent Length and Size: Variables (columns) within a data frame must have consistent lengths for vectors and consistent row counts for matrices. This ensures uniformity across columns in terms of data structure.\nMatrix-Like Operations: While data frames are list-like structures, they can be treated like matrices in many operations. They can be displayed in matrix form, and their rows and columns can be accessed using matrix indexing conventions.\n\n\n\n\nnull \n 9 \n\n\n\n\n\n\n\n\nPlease enable JavaScript to experience the dynamic code cell content on this page.\n\n\n\nPlease enable JavaScript to experience the dynamic code cell content on this page.\n\n\nLanguage objects can be converted to and from lists by the as.list and as.call functions.\nSymbols can be created through the functions as.name and quote.\nThe main difference between language object and expression object is that an expression object can contain several such expressions.\n\n\nPlease enable JavaScript to experience the dynamic code cell content on this page.\n\ntibble or tbl_df is a modernized version of data frame, provided by the tibble package, designed to address some of the shortcomings of traditional data frames.\nThey maintain compatibility with data frames but offer enhanced features and better printing defaults. Here’s how you can use as_tibble() to coerce objects into tibbles:\nKey Characteristics of Tibbles:\n\nLazy Evaluation: Tibbles are lazy, meaning they do not automatically change variable names or types. This characteristic encourages explicit and intentional programming practices, minimizing unexpected changes and errors.\nSurly Behavior: Tibbles complain more assertively than data frames. For example, if you attempt to access a variable that doesn’t exist, a tibble will raise an error, prompting you to address issues earlier in your code development process.\nEnhanced Print Method: Tibbles feature an enhanced printing method that improves readability and usability, especially with large datasets containing complex objects. This makes it easier to interact with and understand data directly from the console or within scripts.\nSimpler Coercion: The as_tibble() function simplifies the process of coercing objects into tibbles compared to as.data.frame() methods. This simplification enhances code clarity and reduces the cognitive load when working with different data structures.\nTibbles do not support row names. They are removed when converting to a tibble or when subsetting:\n\nBenefits of Using Tibbles:\n\nCleaner Code: By enforcing stricter rules and providing clearer error messages, tibbles help maintain cleaner and more expressive code.\nImproved Debugging: Early error reporting and clear feedback on problematic operations facilitate quicker debugging and troubleshooting.\nCompatibility with Modern Data Analysis Tools: Tibbles are designed to integrate seamlessly with modern data analysis tools and packages in R, supporting efficient and effective data manipulation and visualization tasks.\n\n\n\n\nPlease enable JavaScript to experience the dynamic code cell content on this page.\n\nRecycling\nWhen constructing a tibble, only values of length 1 are recycled. The first column with length different to one determines the number of rows in the tibble, conflicts lead to an error:\n\n\nPlease enable JavaScript to experience the dynamic code cell content on this page.\n\n\n\n\n\n\n\nFeature\nMatrix\nDataFrame\nDataTable\nTibble\n\n\n\n\nColumn Types\nHomogeneous\nHeterogeneous\nHeterogeneous\nHeterogeneous\n\n\nMemory Efficiency\nHigh\nModerate\nHigh\nModerate\n\n\nComputation Speed\nFast\nModerate\nVery Fast\nModerate\n\n\nEase of Use for Data Manipulation\nLow\nHigh\nHigh\nHigh\n\n\nIntegration with tidyverse\nNo\nPartial\nPartial\nYes\n\n\nLearning Curve\nLow\nLow\nHigh\nModerate\n\n\n\n\n\n\n\n\n\n\nMissing values\n\nMissing values in R still have a class.(missing numeric, integer, logical, or character missing values.)\nNaN: Mathematically not defined (and always of class numeric).\n\nPlease enable JavaScript to experience the dynamic code cell content on this page.\nNA: Missing value, NA’s still have classes!\nNaN is also NA but not vice versa.",
"crumbs": [
"Home",
"Data Type in R"
]
},
{
"objectID": "datatype.html#control-statement",
"href": "datatype.html#control-statement",
"title": "DAiR Workshop 2024",
"section": "Control Statement",
"text": "Control Statement\n\nControl statement are fundamental aspect of all programming languages, including R.\n\n\n\nControl structures in R allow you to manage the flow of execution for a series of expressions.\nControl flow in R involves managing how code execution proceeds based on conditions and iterations.\nThey enable you to add logic to your R code, making it more dynamic and responsive to different inputs or data features.\nBy using control structures, you can ensure that different R expressions are executed based on certain conditions, rather than always running the same code each time.\nThey are typically used in functions or longer expressions rather than in interactive sessions.\n\nYou can also use control structures outside of functions to understand their behavior and become comfortable with them.\n\n\n\n\n\nHere are some commonly used control structures:\n\nfor loop: Used to execute a loop a specified number of times.\nbreak : Used to terminate the execution of a loop prematurely.\nnext : Used to skip the current iteration of a loop and proceed to the next iteration.\nwhile : Used to execute a loop as long as a condition remains true.\nif and else : Used to test a condition and execute code based on the result.\nrepeat :Used to execute an infinite loop, which must be explicitly terminated with a break statement.\n\nThere are two type of control flow:\n\nChoices (Conditional statements)\nLoops (Iteration)\n\nChoices\nif statement\n\nPlease enable JavaScript to experience the dynamic code cell content on this page.\nelse statement\n\nPlease enable JavaScript to experience the dynamic code cell content on this page.\n\nPlease enable JavaScript to experience the dynamic code cell content on this page.\n\nPlease enable JavaScript to experience the dynamic code cell content on this page.\n\nPlease enable JavaScript to experience the dynamic code cell content on this page.\n\nPlease enable JavaScript to experience the dynamic code cell content on this page.\nInvalid Inputs\n\nThe condition should evaluate to a single TRUE or FALSE.\n\nPlease enable JavaScript to experience the dynamic code cell content on this page.\n\nVectorised if\n\nPlease enable JavaScript to experience the dynamic code cell content on this page.\n\nHandling Missing Values:\nifelse() propagates missing values in its output. If the test condition results in NA, the corresponding output will also be NA\n\nPlease enable JavaScript to experience the dynamic code cell content on this page.\n For example in this code, the NA in x results in \"Missing\" in result .\nOutput Type Consistency:\n\nifelse() expects the yes and no arguments to be of the same type or able to be coerced to the same type.\nMixing different types might lead to unexpected results or coercion that may not align with your expectations.\n\n\nPlease enable JavaScript to experience the dynamic code cell content on this page.\n Here, because \"High\" is a character and 1:4 is numeric, ifelse() coerces the numeric values to characters where the condition is TRUE.\nAlternative Considerations:\n\nIf you have multiple conditions and need to handle various types or more complex scenarios, consider using case_when() from dplyr:\n\nPlease enable JavaScript to experience the dynamic code cell content on this page.\n case_when() offers more flexibility in handling multiple conditions and provides clearer syntax compared to nested ifelse() statement.\n\n\nswitch() statement\n\nThe switch() statement in R is a powerful control structure for handling multiple conditions more compactly than a series of if-else statements.\nIt allows you to select one of several possible actions based on the value of an expression.\nWhen using switch(), it’s important to ensure that unmatched inputs are handled properly to avoid unexpected NULL returns.\n\n```{webr-r}\n# Define a function using switch() to handle multiple conditions\naction <- function(option) {\n switch(option,\n \"add\" = {\n result <- 1 + 1\n paste(\"Adding: 1 + 1 =\", result)\n },\n \"subtract\" = {\n result <- 2 - 1\n paste(\"Subtracting: 2 - 1 =\", result)\n },\n \"multiply\" = {\n result <- 2 * 2\n paste(\"Multiplying: 2 * 2 =\", result)\n },\n \"divide\" = {\n result <- 4 / 2\n paste(\"Dividing: 4 / 2 =\", result)\n },\n stop(\"Invalid option. Please choose one of 'add', 'subtract', 'multiply', 'divide'.\")\n )\n}\n\n# Example usage\nprint(action(\"add\")) # Outputs: \"Adding: 1 + 1 = 2\"\nprint(action(\"subtract\")) # Outputs: \"Subtracting: 2 - 1 = 1\"\nprint(action(\"multiply\")) # Outputs: \"Multiplying: 2 * 2 = 4\"\nprint(action(\"divide\")) # Outputs: \"Dividing: 4 / 2 = 2\"\nprint(action(\"unknown\")) # Throws an error: \"Invalid option. Please choose one of 'add', 'subtract', 'multiply', 'divide'.\"\n```\n Explanation:\n\nThe switch() statement takes a single expression (option in this case) and matches it against several possible cases (\"add\", \"subtract\", \"multiply\", \"divide\").\nFor each case, the corresponding block of code is executed.\nIf none of the cases match, the last component of the switch() statement (stop()) throws an error, ensuring that unmatched inputs do not silently return NULL.\nif multiple inputs should result in the same output, you can leave the right-hand side of the = empty for those cases, allowing the input to “fall through” to the next specified value.\n\nPlease enable JavaScript to experience the dynamic code cell content on this page.\n\n\n\nLoops\n\nR excels at handling repetitive tasks through loops.\nLoops allow you to repeat a set of operations multiple times or until a specified condition is met.\nThere are three main types of loops in R:\n\nThe for loop :\n\nFor loops are indeed versatile and commonly used in R for iterating over sequences or performing repetitive tasks.\nWhile other loop constructs like while loops and repeat loops have their specific use cases, for loops often suffice in practice.\n\nThe while loop\nThe repeat loop.\n\n\n\nFor Loop\nIn R, for loops are a fundamental construct used to iterate over elements of objects like lists or vectors. For example:\nfor each character i in the sequence ‘A’ to ‘J’ do // execute code within curly braces end loop\n\n\nPlease enable JavaScript to experience the dynamic code cell content on this page.\n\nWhile other looping constructs exist, for loops are typically adequate for most data analysis tasks due to their simplicity and effectiveness.\n\n\nPlease enable JavaScript to experience the dynamic code cell content on this page.\n\nWhen iterating over a vector of indices in R, it’s conventional to use short variable names such as i, j, or k.\n\n\nPlease enable JavaScript to experience the dynamic code cell content on this page.\n\n The for loop assigns the item to the current environment, which can overwrite any existing variable with the same name. This means that if you have a variable named i in your current environment and you use i as the loop variable, the original i will be overwritten.\n\nPlease enable JavaScript to experience the dynamic code cell content on this page.\n Explanation:\nThe initial value of i is set to 10.\n\nInside the for loop, i is used as the loop variable and takes on the values from the indices vector (1 to 5).\n\n\n\nAfter the loop, the value of i in the current environment is the last value assigned in the loop, which is 5, thus overwriting the original value of 10.\nTo avoid overwriting variables unintentionally, you can use a different variable name or explicitly manage the scope of your variables:\n\n\nPlease enable JavaScript to experience the dynamic code cell content on this page.\n\nyou can terminate a for loop early using either next or break statements:\n\nnext exits the current iteration and proceeds to the next iteration of the loop.\n\nPlease enable JavaScript to experience the dynamic code cell content on this page.\n Explanation:\n\nThe next statement is used to skip even numbers. When i is even, the next statement is executed, and the loop proceeds to the next iteration without executing the print statement.\nAs a result, only odd numbers are printed: 1, 3, 5, 7, 9.\n\n\n\n\nbreak exits the entire for loop immediately.\n\nPlease enable JavaScript to experience the dynamic code cell content on this page.\n Explanation:\n\nThe break statement is used to exit the loop when i is greater than 5.\nAs a result, the loop stops after printing 1, 2, 3, 4, and 5.\n\nWhen using for loops in R, there are three common pitfalls to be aware of:\n\nPreallocating Output Containers:\n\nIf you are generating data inside a loop, it’s crucial to preallocate the output container. Otherwise, the loop will be very slow.\nYou can use the vector() function to preallocate the output container.\n\nPlease enable JavaScript to experience the dynamic code cell content on this page.\nAvoiding 1:length(x):\n\nUsing 1:length(x) can fail in unhelpful ways if x has length 0, resulting in errors\n\nPlease enable JavaScript to experience the dynamic code cell content on this page.\nThis occurs because : works with both increasing and decreasing sequences. Instead, use seq_along(x), which always returns a value the same length as x.\n\nPlease enable JavaScript to experience the dynamic code cell content on this page.\n\nHandling S3 Vectors:\n\nWhen iterating over S3 vectors, loops typically strip the attributes. To avoid this issue, call [[ yourself to ensure attributes are preserved.\n\nPlease enable JavaScript to experience the dynamic code cell content on this page.\n\n\n\nUsing seq_along() for safe iteration.\n\nThere are two related tools with more flexible specifications:\n\nwhile(condition) action:\n\nThis performs an action while the condition is TRUE.\n\nPlease enable JavaScript to experience the dynamic code cell content on this page.\n\nrepeat(action):\n\nThis repeats the action forever (i.e., until it encounters break)\n\nPlease enable JavaScript to experience the dynamic code cell content on this page.\nR does not have an equivalent to the do {action} while (condition) syntax found in other languages.\nYou can rewrite any for loop to use while instead, and you can rewrite any while loop to use repeat, but the converses are not true.\n\nThis means while is more flexible than for, and repeat is more flexible than while\n\nYou shouldn’t need to use for loops for data analysis tasks, as map() and apply() functions already provide less flexible solutions to most problems.\n\n\n\n\n\nNested for loops\nWe can nest for loops inside one another.\nThis allows you to perform more complex iterations and computations where multiple levels of looping are required.\n\nNested for loops involve placing one or more for loops inside the body of another for loop.\nEach inner loop executes its entire cycle for every iteration of the outer loop.\nThis nested structure is useful for iterating over multidimensional data structures like matrices or performing repetitive tasks that involve multiple levels of iteration.\n\n\nPlease enable JavaScript to experience the dynamic code cell content on this page.\n\n\nLet’s proceed with Exercise 3.",
"crumbs": [
"Home",
"Data Type in R"
]
},
{
"objectID": "datatype.html#nested-for-loops",
"href": "datatype.html#nested-for-loops",
"title": "DAiR Workshop 2024",
"section": "Nested for loops",
"text": "Nested for loops\nWe can nest for loops inside one another.\nThis allows you to perform more complex iterations and computations where multiple levels of looping are required.\n\nNested for loops involve placing one or more for loops inside the body of another for loop.\nEach inner loop executes its entire cycle for every iteration of the outer loop.\nThis nested structure is useful for iterating over multidimensional data structures like matrices or performing repetitive tasks that involve multiple levels of iteration.\n\n\nPlease enable JavaScript to experience the dynamic code cell content on this page.\n\n\nLet’s proceed with Exercise 3.",
"crumbs": [
"Home",
"Data Type in R"
]
},
{
"objectID": "datatype.html#functions-wickham2019advanced",
"href": "datatype.html#functions-wickham2019advanced",
"title": "DAiR Workshop 2024",
"section": "Functions Wickham (2019)",
"text": "Functions Wickham (2019)\nTo comprehend functions in R thoroughly, it’s essential to grasp two key concepts:\n\nFunction Components: Functions consist of three primary components:\n\nFormals (formals()):\n\nThis represents the list of arguments defined when the function is created. Arguments determine how you call and pass data into the function. They are inputs provided to the function.\n\nBody (body()):\n\nThe body contains the actual code that executes when the function is called. It defines what the function does with the provided arguments. The sequence of expressions that define what the function does.\n\nEnvironment (environment()):\n\nThe environment specifies the context or scope in which the function operates. It dictates how the function accesses and interacts with data and other objects.\n\n\n\nThe environment is implicitly determined based on where the function is defined. If the function is defined within the global environment, it inherits that environment unless specified otherwise..\n\n\nPrimitive Base Functions: Despite the general rule that functions are defined in R, there are exceptions. A subset of functions known as “primitive” base functions is implemented directly in C for efficiency reasons.\n\nSuch as sum() as type builtin and [ as type special,which are exceptions to the standard function structure.\nThey directly call C code for execution and offering optimized performance for basic operations like summing elements or extracting subsets of data.\nHence, when you check their attributes using formals(), body(), or environment() functions, they typically return NULL because these attributes are not applicable to primitive functions\nPrimitive functions in R are typically found in the base package of R.\n\nFunctions as Objects: Similar to vectors and other data types, functions are objects in R.\n\nR does not require special syntax for defining and naming functions.\n\nPlease enable JavaScript to experience the dynamic code cell content on this page.\nYou create a function object using the function keyword and then bind it to a name using the assignment operator <-.\nThis flexibility allows for dynamic and powerful programming capabilities within R.\nsrcref is useful for printing or displaying the original source code that was used to create the function.\nAnonymous functions, also known as lambda functions, e useful in situations where you need a function for a short period or when it’s not necessary to assign a name.\n\nPlease enable JavaScript to experience the dynamic code cell content on this page.\n\nThis example demonstrate the use of function lapply along with anonymous functions defined using function(x).\n\n\nPutting functions in a list can be very useful, especially when you need to store multiple functions together for organizational purposes or to pass them as arguments to other functions.\n\nPlease enable JavaScript to experience the dynamic code cell content on this page.\n\nIn the above example:\n\nWe define three functions (square, cube, and sqrt).\nWe create a list function_list containing these functions, where each function is assigned a name within the list (square, cube, sqrt).\nWe then call each function from the list using $ notation (function_list$square, function_list$cube, function_list$sqrt).\n\n\n\n\nIf we have the arguments for a function already stored in a data structure, such as a list or a vector, we can still call the function using the do.call() function in R.\n\nPlease enable JavaScript to experience the dynamic code cell content on this page.\n\nUnderstanding these aspects is fundamental for mastering function usage and manipulation in R.\nBase R provides two ways to compose multiple function calls: nesting and piping.\n\nNesting\nIt is straightforward but can become unwieldy with complex chains of functions.\n\nPlease enable JavaScript to experience the dynamic code cell content on this page.\nIn this example:\n\nmean(data) computes the mean of the data.\ndata - mean(data) computes the deviations from the mean.\n(data - mean(data))^2 squares the deviations.\nmean((data - mean(data))^2) computes the mean of the squared deviations (variance).\nsqrt(mean((data - mean(data))^2)) takes the square root of the variance to get the standard deviation.\n\nUsing a Sequence of Function Calls with Intermediate Results\n\nYou can store intermediate results in variables, which can make the code more readable:\n\n```{webr-r}\n# Compute the population standard deviation\nx <- c(1, 2, 3, 4, 5)\n\n# Step 1: Compute the mean of x\nmean_x <- mean(x)\n\n# Step 2: Compute the squared deviations from the mean\nsquared_deviations <- (x - mean_x)^2\n\n# Step 3: Compute the mean of the squared deviations\nmean_squared_deviations <- mean(squared_deviations)\n\n# Step 4: Take the square root to get the population standard deviation\npopulation_sd <- sqrt(mean_squared_deviations)\n\nprint(population_sd)\n#> [1] 1.414214\n```\nPiping\nOffers improved readability and maintainability by breaking down complex operations into a sequence of simple steps.\n\nintroduced in the magrittr package and later incorporated into dplyr.\nThe pipe operator %>% passes the result of one function call as the first argument to the next function.\n\nPlease enable JavaScript to experience the dynamic code cell content on this page.\nIn this example:\n\ndata %>% starts the pipeline with the data.\n-(mean(.)) subtracts the mean of data from each element.\n^(2) squares each deviation.\nmean() computes the mean of the squared deviations.\nsqrt() takes the square root of the variance to get the standard deviation.\n\nLexical Scoping\n\nScoping determines how values are found in an R environment when a name is referenced.\nLexical scoping, in particular, refers to how R resolves the value of a variable name based on where the variable is defined in the source code, rather than where it is called.\n\nPlease enable JavaScript to experience the dynamic code cell content on this page.\n Explanation\nIn this example, we have a variable x defined in the global environment and another variable x defined inside the function f(). When we call f(), the function returns the value of x defined within its own scope, which is 20.\n\nGlobal Environment:\n\nx <- 10: A variable x is assigned the value 10.\n\nFunction Definition:\n\nf <- function() { ... }: A function f is defined. Inside this function:\n\nx <- 20: A new variable x is assigned the value 20 within the local scope of the function.\nreturn(x): The function returns the value of x from its local scope.\n\n\nFunction Call:\n\nresult <- f(): The function f() is called, and the returned value (20) is assigned to result.\n\nOutput:\n\nprint(result): This prints 20 to the console.\n\n\n\nThe four primary rules of R’s lexical scoping:\n\n- **Name Masking**:\n\n - If a variable name is defined in multiple nested environments (e.g., global environment and function's local environment), the closest (most nested) definition takes precedence. This is known as name masking.\n\n ```{webr-r}\n x <- 10 # Global environment\n f <- function() {\n x <- 20 # Local environment of f()\n print(x) # Prints 20, not the global 10\n }\n ```\n\n- **Functions versus Variables**:\n\n - Functions and variables are treated similarly in scoping. They both follow lexical scoping rules, meaning their visibility is determined by their definition location in the source code.\n\n ```{webr-r}\n x <- 10\n g <- function() {\n print(x) # Accesses the global variable x\n }\n ```\n\n- **A Fresh Start**:\n\n - Each function call creates a new local environment with a fresh set of bindings (variables). This means each function call operates with its own set of variables that are independent of other function calls.\n\n ```{webr-r}\n x <- 10\n h <- function() {\n x <- 20\n i <- function() {\n print(x) # Accesses x from the local environment of h()\n }\n i()\n }\n ```\n\n- **Dynamic Lookup**:\n\n - Variables are looked up dynamically based on the scope hierarchy at the time of execution, not at the time of definition. This means that a variable's value is determined by the environment it is currently being accessed from, not where it was defined.\n\n ```{webr-r}\n x <- 10\n j <- function() {\n print(x) # Accesses the global variable x at runtime\n }\n ```\n\nLazy evaluation\n\nLazy evaluation refers to the behavior where function arguments are not evaluated until they are actually needed or accessed within the function’s body.\nThis concept ensures efficiency by delaying computation until necessary.\n\nPlease enable JavaScript to experience the dynamic code cell content on this page.\n In this example:\n\nThe function f is defined to accept an argument x.\nInside f, x is not used in any computation or operation.\nWhen f is called with f(x = 10), the argument x is passed but never accessed within the function’s body.\n\nDespite x being provided as an argument when calling f, no error occurs because R does not evaluate x unless it is explicitly used within the function. This demonstrates lazy evaluation: R postpones the evaluation of x until it is actually needed inside the function.\n\nPromises\n\nPromises are integral to lazy evaluation.\nThey encapsulate the expression and environment where an expression should be evaluated, deferring its computation until its value is explicitly needed.\n\nPlease enable JavaScript to experience the dynamic code cell content on this page.\n Explanation:\n\nPromise Creation: In function f, x + y forms a promise. It represents the expression to be evaluated (x + y) and the environment where it should be evaluated (the environment where f is called).\nDeferred Evaluation: When g calls f(z, 5), z and 5 are passed as arguments to f. However, x + y (the promise) is not immediately evaluated. Instead, it remains as a promise until its value is explicitly needed.\nEager vs Lazy Evaluation: R will evaluate the promise (compute x + y) only when the result of f(z, 5) is actually required, such as when result is assigned the value returned by g(6).\nEnvironment Sensitivity: Promises are evaluated in the environment where the function is called (g in this case), ensuring that the correct values of variables (z and 5) are used at evaluation time.Missing\n\n\nMissing Argument\n\nThe missing() function is useful for determining whether an argument passed to a function is explicitly provided by the user or if it defaults to a predefined value within the function definition.\n\nPlease enable JavaScript to experience the dynamic code cell content on this page.\n Explanation:\n\nFunction Definition: my_function is defined with x having a default value of 10.\nUsing missing(): Inside my_function, missing(x) checks if x was provided explicitly by the user or if it defaults to 10.\nCalling my_function():\n\nWhen called without arguments (my_function()), x defaults to 10. missing(x) returns TRUE because x is not provided by the user.\nTherefore, the function prints a message indicating that the default value of x is being used.\n\nCalling my_function(20):\n\nHere, x is explicitly provided as 20. missing(x) returns FALSE because x is provided by the user.\nThe function prints a message showing that x was indeed provided by the user with the value 20.\n\n\nThe sample() function in R requires at least two arguments:\n\nx: This argument specifies the vector or set of values from which to sample.\nsize: This argument specifies the number of samples to draw from x.\n\nThere is also an optional argument:\n\nreplace: This argument indicates whether sampling should be done with or without replacement (default is replace = FALSE).\n\n\nPlease enable JavaScript to experience the dynamic code cell content on this page.\nThe %||% infix function in R is typically used to simplify expressions where you want to use a default value or fallback to an alternative if the left-hand side is NULL.\nThis can be particularly useful in defining default arguments or handling optional parameters in functions.\n\nPlease enable JavaScript to experience the dynamic code cell content on this page.\n Explanation:\n\nDefinition of %||%: Defines a custom infix function %||% that checks if x is NULL or not. If x is not NULL, it returns x; otherwise, it returns default.\nRedefined sample2 function: Uses %||% to provide default values for size and replace parameters:\n\nsize %||% 1: If size is not provided (NULL), default to 1.\nreplace %||% FALSE: If replace is not provided (NULL), default to FALSE.\n\nExamples:\n\nsample2(1:10): Uses default size = 1 and replace = FALSE.\nsample2(letters, size = 3, replace = TRUE): Specifies size = 3 and replace = TRUE.\nsample2(LETTERS, size = 5): Uses size = 5 with default replace = FALSE.\n\n\nwhen using %||%, the right-hand side (the default value or fallback) will only be evaluated if the left-hand side is NULL.\n\nExiting Function\nFunctions can return values either implicitly or explicitly:\n\nImplicit Returns: Implicit return occurs when the last evaluated expression within the function is automatically returned as its result\n\nPlease enable JavaScript to experience the dynamic code cell content on this page.\nIn this example, a + b is the last expression in the function add_numbers, so its result (8) is implicitly returned when the function is called.\nExplicit Returns:\nExplicit return involves using the return() function to explicitly specify the value to be returned from the function. This is useful when you want to return early from a function or when the return value isn’t the last evaluated expression:\n\nPlease enable JavaScript to experience the dynamic code cell content on this page.\n In this example, return(sum_numbers / length(numbers)) explicitly returns the calculated average. The return() function can be used anywhere within the function body to specify the return value.\n\nInvisible Values:\n\n- functions typically return values that are visible when called interactively. This means that the result of calling the function will be printed in the console or displayed in some manner.\n\n```{webr-r}\nsquare <- function(x) {\n x^2 # Returns the square of x\n}\n\n# Calling the function and displaying the result\nsquare(5)\n# Output: 25\n```\n\n{width=\"76\"} In this example, when `square(5)` is called, `25` is printed as output because the function `square` returns the square of its input `x`.\n\n- sometimes you may want a function to return a value invisibly, meaning it is computed and returned as the function result but not printed or displayed by default.\n\n- This is useful when you want to perform a computation within a function but don't want the result to clutter the console output or interfere with subsequent operations.\n\n ```{webr-r}\ncompute_sum <- function(a, b) {\n result <- a + b\n invisible(result) # Return result invisibly\n}\n\n# Calling the function and capturing the result\nsum_result <- compute_sum(10, 20)\nprint(sum_result) # Output: 30\n```\n\n {width=\"78\"} In this example, `compute_sum(10, 20)` calculates the sum `30`, but because `invisible(result)` is used, the result `30` is returned invisibly. This means it's computed and can be assigned to a variable (`sum_result`), but it doesn't print directly to the console unless explicitly printed or used.\n\n- `withVisible()` is a function that allows you to return a value along with a visibility flag.\n\n ```{webr-r}\ncompute_product <- function(x, y) {\n result <- x * y\n visible_result <- withVisible(result) # Capture result with visibility flag\n return(visible_result)\n}\n\n# Example usage:\nprod_result <- compute_product(7, 8)\n\n# Checking the returned object\nprod_result\n```\n\nThe stop() function is used to terminate the execution of a function immediately and throw an error message.\n\nPlease enable JavaScript to experience the dynamic code cell content on this page.\nExit handlers:\n\nExit handlers are useful for ensuring that certain actions are performed whenever a function exits, regardless of whether it exits normally or due to an error:\n\nPlease enable JavaScript to experience the dynamic code cell content on this page.\n In this example:\n\nThe modify_global_state() function modifies the global state by creating a temporary variable temp_var.\non.exit() is used to set up an exit handler that will execute regardless of how the function exits.\nInside the exit handler, you can perform cleanup actions such as removing temporary variables (rm(list = ls(pattern = \"^temp_\"))).\nThe function includes a commented-out line (stop(\"Error: Simulation of an error condition.\")) to simulate an error condition. If this line is uncommented, the exit handler will still execute.\n\n\nPrefix\n\n```{webr-r}\n# Example function with named arguments\nprefix_example <- function(arg1, argument_long_name, arg3) {\n cat(\"Argument 1:\", arg1, \"\\n\")\n cat(\"Argument with long name:\", argument_long_name, \"\\n\")\n cat(\"Argument 3:\", arg3, \"\\n\")\n}\n\n# Calling the function using exact names\nprefix_example(arg1 = 1, argument_long_name = 2, arg3 = 3)\n\n# Using unique prefixes (partial matching)\nprefix_example(a = 1, argument_long = 2, arg3 = 3)\n\n# Arguments by position\nprefix_example(1, 2, 3)\n```\n In this example:\n\nThe prefix_example function takes three arguments: arg1, argument_long_name, and arg3.\nYou can call prefix_example using exact names (arg1 =, argument_long_name =, arg3 =), which is straightforward and explicit.\nR also supports partial matching. For instance, a = 1 matches arg1, and argument_long = 2 matches argument_long_name because it is the only argument starting with argument_long.\nLastly, you can call the function by providing arguments in the order of their definition (1 for arg1, 2 for argument_long_name, 3 for arg3).\nYou can create a custom infix function using % symbols:\n\nPlease enable JavaScript to experience the dynamic code cell content on this page.\n In this example:\n\nThe function %^% is defined to compute the exponentiation of base raised to the power of exponent.\nTo define an infix function, the function name is enclosed in backticks (``), and %^% indicates the custom infix operator for exponentiation.\nWhen you use %^%, it calculates 2^3, resulting in 8.\nwhen defining infix functions, their names can include any sequence of characters except for %. Here’s an example illustrating how to define and use an infix function with special characters:\n\n```{webr-r}\n# Define an infix function with special characters\n`%+%` <- function(x, y) {\n paste(x, \"+\", y)\n}\n\n# Using the infix function\nresult <- \"Hello\" %+% \"World\"\nprint(result) # Outputs: \"Hello + World\"\n```\n In this example:\n\nThe function %+% is defined to concatenate two strings x and y with a “+” sign in between.\nThe function name %+% is enclosed in backticks (``) to indicate it’s an infix operator.\nWhen calling the infix function, such as \"Hello\" %+% \"World\", you don’t need to escape special characters like + within the function call itself.\ninfix operators follow default precedence rules where they are composed from left to right. This means that when multiple infix operators are used in an expression, they are evaluated based on their position and precedence.\n\nPlease enable JavaScript to experience the dynamic code cell content on this page.\n\nReplacement functions are denoted by their special name format xxx<-, where xxx is the name of the function they replace.\n\nThese functions modify their arguments in place by assigning a new value.\nThey must have arguments named x (the object to be modified) and value (the new value to assign), and they should return the modified object.\n\nPlease enable JavaScript to experience the dynamic code cell content on this page.\n\n\n\n\n\n\n\nSpecial_Form\nPrefix_Form\n\n\n\n\n`(`(x)\n(`(x)\n\n\n`{`(x)\n{`(x)\n\n\n`[`(x, i)\n[`(x, i)\n\n\n`[[`(x, i)\n[[`(x, i)\n\n\n`if`(cond, true)\nif (cond) true\n\n\n`if`(cond, true, false)\nif (cond) true else false\n\n\n`for`(var, seq, action)\nfor(var in seq) action\n\n\n`while`(cond, action)\nwhile(cond) action\n\n\n`repeat`(expr)\nrepeat(expr)\n\n\n`next`()\nnext()\n\n\n`break`()\nbreak()\n\n\n`function`(alist(arg1, arg2), body, env)\nfunction(arg1, arg2) {body}",
"crumbs": [
"Home",
"Data Type in R"
]
},
{
"objectID": "stat.html",
"href": "stat.html",
"title": "DAiR Workshop 2024",
"section": "",
"text": "Author: Dr. Hamed Abdollahi \n PI: Dr. Homayoun Valafar",
"crumbs": [
"Home",
"Statistics in R"
]
},
{
"objectID": "USL.html",
"href": "USL.html",
"title": "DAiR Workshop 2024",
"section": "",
"text": "Bioinformatics and Data Science Summer Workshops 2024\n\n\n\n \n \n \n \n \n \n \n Author: Dr. Hamed Abdollahi \n PI: Dr. Homayoun Valafar",
"crumbs": [
"Home",
"learning in R"
]
},
{
"objectID": "ml.html",
"href": "ml.html",
"title": "DAiR Workshop 2024",
"section": "",
"text": "Bioinformatics and Data Science Summer Workshops 2024\n\n\n\n \n \n \n \n \n \n \n Author: Dr. Hamed Abdollahi \n PI: Dr. Homayoun Valafar",
"crumbs": [
"Home",
"ML in R"
]
},
{
"objectID": "index.html#sec-what-is-r",
"href": "index.html#sec-what-is-r",
"title": "DAiR Workshop 2024",
"section": "What is R",
"text": "What is R\n\nR is a comprehensive software suite designed for data manipulation, computation, and graphical visualization.\nIt is an open source versatile environment utilized for newly developing methods of interactive data analysis.\nR can be seen as an implementation of the S language. The S language also serves as the foundation for the S-Plus systems.\nThe programming languages S (1985) , which received the ACM Software Systems Award in 19981, developed by John M. Chambers(Chambers 1998).\nIn 1992, George Ross Ihaka and Robert Gentleman, from the University of Auckland, developed R based on the programming languages S and Scheme (1975).\nGeorge Ross Ihaka and Robert Gentleman published their experience as a statistical computing language in 1996(Ihaka and Gentleman 1996).\nThe inaugural “stable beta2” version, denoted as v1.0, was officially launched on February 29, 20003 .\nR features a vast library primarily written in C, C++, Fortran, and R.\nR facilitates tasks such as linear and nonlinear modeling, statistical tests, time series analysis, classification, clustering, and more.\nR has emerged as the leading statistical software in the scientific community.\nIt excels in analyzing data and producing insights for companies and institutions, empowering them to make informed business decisions.",
"crumbs": [
"Home",
"DAiR Workshop 2024"
]
},
{
"objectID": "Scripts/Bioinformatics_Visualization_Part1.html",
"href": "Scripts/Bioinformatics_Visualization_Part1.html",
"title": "Bioinformatics Visualization in R - Part 1",
"section": "",
"text": "Lecture 1: Introduction to Visualization and Basic Plots\nObjective: - Introduce basic bioinformatics visualization techniques using R Histogram, Scatter Plot, Box Plot, Line Plot\n- Overview of syntax using simulated data - Explore basic plots using nhanes data. - Exercise 1\nLoad necessary libraries\n\nlibrary(ggplot2)\nlibrary(dplyr)\n\nWarning: package 'dplyr' was built under R version 4.3.2\n\n\n\nAttaching package: 'dplyr'\n\n\nThe following objects are masked from 'package:stats':\n\n filter, lag\n\n\nThe following objects are masked from 'package:base':\n\n intersect, setdiff, setequal, union\n\nlibrary(readr)\n\nWarning: package 'readr' was built under R version 4.3.2\n\nlibrary(tidyr)\n\nWarning: package 'tidyr' was built under R version 4.3.2\n\n\nGenerate synthetic data\n\n# set.seed ensures that the sequence of random numbers generated can be reproduced.\nset.seed(123)\n\ndata <- data.frame(\n Time = 1:50,\n # rnorm() = random normal is used to generate random numbers from a normal distribution.\"\n X = rnorm(50, mean = 5, sd = 2),\n Y = 2 * rnorm(50, mean = 5, sd = 2) + rnorm(50),\n # c(\"A\", \"B\") creates a vector containing the elements \"A\" and \"B\"\n # each = 25 specifies that each element in the vector should be repeated 25 times\n Group = rep(c(\"A\", \"B\"), each = 25)\n)\n\n\nHistogram Plot: Histograms are useful to show the distribution of a single continuous variable\n\n\n# Create the histogram using ggplot2\nhistogram_plot <- ggplot(data, aes(x = X)) +\n geom_histogram(binwidth = (max(data$X) - min(data$X)) / 10, \n fill = \"purple\", color = \"white\") +\n ggtitle(\"Histogram\") +\n xlab(\"Value\") +\n theme_minimal() +\n theme(\n plot.background = element_rect(fill = \"white\"),\n panel.background = element_rect(fill = \"white\")\n )\n\n# Display the plot\nhistogram_plot\n\n\n\n\n\n\n\n# Save the plot to a file\nggsave(\"3_histogram_plot.png\", plot = histogram_plot, width = 8, height = 6, dpi = 300)\n\n\nScatter Plot: Scatter plots are useful to show the relationship between two continuous variables\n\n\n# Create the scatter plot with a white background\nScatter_plot <- ggplot(data, aes(x = X, y = Y)) +\n geom_point() +\n ggtitle(\"Scatter Plot\") +\n xlab(\"X-axis\") +\n ylab(\"Y-axis\") \n\n# Display the plot\nScatter_plot\n\n\n\n\n\n\n\n# Save the plot to a file\nggsave(\"1_scatter_plot.png\", plot = Scatter_plot, width = 8, height = 6, dpi = 300)\n\n\nBox Plot: Box plots are useful to show the distribution of a continuous variable\n\n\n# Box Plot\n# Create the box plot\nBox_plot <- ggplot(data, aes(x = Group, y = Y, fill = Group)) +\n geom_boxplot() +\n ggtitle(\"Box Plot\") +\n xlab(\"Group\") +\n ylab(\"Value\") +\n scale_fill_manual(values = c(\"red\", \"green\")) +\n theme_minimal() +\n theme(\n plot.background = element_rect(fill = \"white\"),\n panel.background = element_rect(fill = \"white\")\n )\n\n# Display the plot\nBox_plot\n\n\n\n\n\n\n\n# Save the plot to a file\nggsave(\"2_box_plot.png\", plot = Box_plot, width = 8, height = 6, dpi = 300)\n\n\nLine Plot: Line plots are useful to show trends over time or another continuous variable\n\n\n# Create the line plot using ggplot2\ndata$Value <- cumsum(rnorm(50))\nline_plot <- ggplot(data, aes(x = Time, y = Value)) +\n geom_line(color = \"orange\", linewidth = 1.5) + # Set line color and thickness\n ggtitle(\"Line Plot\") +\n xlab(\"Time\") +\n ylab(\"Value\") +\n theme_minimal() +\n theme(\n plot.background = element_rect(fill = \"white\"),\n panel.background = element_rect(fill = \"white\")\n )\n\n# Display the plot\nprint(line_plot)\n\n\n\n\n\n\n\n# Save the plot to a file\nggsave(\"4_line_plot.png\", plot = line_plot, width = 8, height = 6, dpi = 300)\n\nLoad a healthcare dataset: nhanes (National Health and Nutrition Examination Survey)\n\n# Actual Dataset Read the data from the provided URL\nNHANES <- read_csv(\"https://raw.githubusercontent.com/GTPB/PSLS20/master/data/NHANES.csv\", show_col_types = FALSE)\n\n# Extract only the columns ID, Age, BMI, and BloodPressure\nnhanes_subset <- NHANES %>%\n select(ID, Age, BMI, BloodPressure = BPSysAve) %>%\n distinct(ID, .keep_all = TRUE) %>%\n drop_na()\n\n# Display the first few rows of the subset\nprint(head(nhanes_subset))\n\n# A tibble: 6 × 4\n ID Age BMI BloodPressure\n <dbl> <dbl> <dbl> <dbl>\n1 51624 34 32.2 113\n2 51630 49 30.6 112\n3 51638 9 16.8 86\n4 51646 8 20.6 107\n5 51647 45 27.2 118\n6 51654 66 23.7 111\n\n# Write the cleaned dataset to a CSV file\nwrite_csv(nhanes_subset, \"health_data.csv\")\n\n# Display summary of the cleaned dataset\nprint(summary(nhanes_subset))\n\n ID Age BMI BloodPressure\n Min. :51624 Min. : 8.0 Min. :12.89 Min. : 76 \n 1st Qu.:56548 1st Qu.:22.0 1st Qu.:22.65 1st Qu.:106 \n Median :61574 Median :39.0 Median :26.63 Median :116 \n Mean :61623 Mean :40.3 Mean :27.58 Mean :118 \n 3rd Qu.:66765 3rd Qu.:56.0 3rd Qu.:31.30 3rd Qu.:127 \n Max. :71915 Max. :80.0 Max. :81.25 Max. :226 \n\n\nVisualization\n\nHistogram\n\n\n# Filter out non-finite values from the BMI column\nnhanes_subset <- nhanes_subset %>%\n filter(is.finite(BMI))\n\n# Create a histogram of BMI with more ticks on the axes\nggplot(nhanes_subset, aes(x = BMI)) +\n geom_histogram(binwidth = 2, fill = \"red\", color = \"white\") +\n ggtitle(\"Histogram of BMI\") +\n xlab(\"BMI\") +\n ylab(\"Frequency\") +\n theme_minimal() + # Apply a minimal theme for a clean look\n theme(\n plot.background = element_rect(fill = \"white\"),\n panel.background = element_rect(fill = \"white\")\n ) +\n xlim(0, 60) + # Trim the x-axis to show values between 10 and 60\n ylim(0, 800) + # Trim the y-axis to show values between 0 and 800\n scale_x_continuous(breaks = seq(0, 60, by = 10), limits = c(10, 60)) + # More ticks on the x-axis\n scale_y_continuous(breaks = seq(0, 800, by = 50)) # More ticks on the y-axis\n\nScale for x is already present.\nAdding another scale for x, which will replace the existing scale.\nScale for y is already present.\nAdding another scale for y, which will replace the existing scale.\n\n\nWarning: Removed 12 rows containing non-finite outside the scale range\n(`stat_bin()`).\n\n\nWarning: Removed 2 rows containing missing values or values outside the scale range\n(`geom_bar()`).\n\n\n\n\n\n\n\n\n\n\nScatter Plot:\n\n\n# Create a scatter plot of BMI vs BloodPressure\n# Sample 10% of the data points\nnhanes_sampled_data <- nhanes_subset %>% sample_frac(0.1)\n\n# Create a scatter plot of BMI vs BloodPressure with the sampled data\nggplot(nhanes_sampled_data, aes(x = BMI, y = BloodPressure)) +\n geom_point(shape = 19, color = \"blue\") +\n ggtitle(\"Scatter Plot of BMI vs Blood Pressure\") +\n xlab(\"BMI\") +\n ylab(\"Blood Pressure\") +\n theme_minimal() + # Apply a minimal theme with a white background\n theme(\n plot.background = element_rect(fill = \"white\"),\n panel.background = element_rect(fill = \"white\")\n )\n\n\n\n\n\n\n\n\n\nBox Plot:\n\n\n# Create a box plot of BloodPressure by Age groups:\nnhanes_sampled_data <- nhanes_sampled_data %>%\n mutate(AgeGroup = cut(Age, breaks = c(20, 40, 60, 80), \n labels = c(\"20-40\", \"40-60\", \"60-80\")))\n\n# Create a box plot of BloodPressure by Age groups with colors\nggplot(nhanes_sampled_data, aes(x = AgeGroup, y = BloodPressure, fill = AgeGroup)) +\n geom_boxplot() +\n ggtitle(\"Box Plot of Blood Pressure by Age Group\") +\n xlab(\"Age Group\") +\n ylab(\"Blood Pressure\") +\n scale_fill_manual(values = c(\"20-40\" = \"red\", \"40-60\" = \"green\", \"60-80\" = \"blue\")) +\n theme_minimal() +\n theme(\n plot.background = element_rect(fill = \"white\"),\n panel.background = element_rect(fill = \"white\")\n )\n\n\n\n\n\n\n\n\n\nLine Plot:\n\n\n# For this example, we'll simulate some time series data\ntime_series_data <- data.frame(\n Time = 1:100,\n Value = cumsum(rnorm(100))\n)\n# Create a line plot of the time series data\nggplot(time_series_data, aes(x = Time, y = Value)) +\n geom_line(color = \"orange\", linewidth = 1.5) +\n ggtitle(\"Line Plot of Simulated Time Series Data\") +\n xlab(\"Time\") +\n ylab(\"Value\") +\n theme_minimal() +\n theme(\n plot.background = element_rect(fill = \"white\"),\n panel.background = element_rect(fill = \"white\")\n )\n\n\n\n\n\n\n\n\n—————————————Assignment 1: Part 1——————————————————–\nDr. Kate is investigating an illness affecting a group of individuals. She needs your help to visualize the nhanes data and uncover hidden patterns.\n\nScatter Plot Investigation: Dr. Kate suspects that age might influence BMI in her patients. Create a scatter plot using the nhanes dataset to visualize the relationship between Age and BMI. Identify any patterns or trends that might suggest an age-related trend in BMI.\n\n\n# Solution a\n\n\n# Hint: Look for clusters or patterns suggesting that certain age groups are more prone to higher or lower BMI, indicating lifestyle or metabolic factors.\n\n\nBox Plot Analysis: Dr. Kate wants to determine if certain age groups are at higher risk for elevated blood pressure. Generate a box plot for BloodPressure by AgeGroup in the nhanes dataset. Identify any age groups with higher or more variable blood pressure, indicating a health risk.\n\n\n# Solution b\n\n\n# Hint: Notice any age group with outliers or higher blood pressure, suggesting that this group is at higher risk of the mysterious illness.\n\n\nHistogram Examination: Dr. Kate is also interested in the distribution of BMI among her patients. Create a histogram of BMI. Analyze the distribution of BMI levels and identify common ranges and any outliers.\n\n\n# Solution c\n\n\n# Hint: Identify common BMI ranges and any outliers. Individuals with significantly high or low BMI might be suffering from the mysterious illness, possibly linked to trends observed in blood pressure and age group"
},
{
"objectID": "Scripts/Bioinformatic_Visulaization_Part2.html",
"href": "Scripts/Bioinformatic_Visulaization_Part2.html",
"title": "Bioinformatics Visualization in R - Part 2",
"section": "",
"text": "Lecture 2: Introduction to Visualization\nObjective: - Explore advanced visualization techniques and create more complex bioinformatics plots using biological data. Density Plot, Violin Plot, Dendogram, Heatmap - Overview of syntax with simulated data - Explore plots using iris dataset. - Exercise 2\nLoad necessary libraries\n\nif (!require(\"ggplot2\")) install.packages(\"ggplot2\")\n\nLoading required package: ggplot2\n\nif (!require(\"GGally\")) install.packages(\"GGally\")\n\nLoading required package: GGally\n\n\nRegistered S3 method overwritten by 'GGally':\n method from \n +.gg ggplot2\n\nif (!require(\"pheatmap\")) install.packages(\"pheatmap\")\n\nLoading required package: pheatmap\n\nif (!require(\"dendextend\")) install.packages(\"dendextend\")\n\nLoading required package: dendextend\n\n\n\n---------------------\nWelcome to dendextend version 1.17.1\nType citation('dendextend') for how to cite the package.\n\nType browseVignettes(package = 'dendextend') for the package vignette.\nThe github page is: https://github.com/talgalili/dendextend/\n\nSuggestions and bug-reports can be submitted at: https://github.com/talgalili/dendextend/issues\nYou may ask questions at stackoverflow, use the r and dendextend tags: \n https://stackoverflow.com/questions/tagged/dendextend\n\n To suppress this message use: suppressPackageStartupMessages(library(dendextend))\n---------------------\n\n\n\nAttaching package: 'dendextend'\n\n\nThe following object is masked from 'package:stats':\n\n cutree\n\nif (!require(\"ggridges\")) install.packages(\"ggridges\")\n\nLoading required package: ggridges\n\nlibrary(dendextend)\nlibrary(ggplot2)\nlibrary(GGally)\nlibrary(pheatmap)\nlibrary(reshape2)\nlibrary(dplyr)\n\nWarning: package 'dplyr' was built under R version 4.3.2\n\n\n\nAttaching package: 'dplyr'\n\n\nThe following objects are masked from 'package:stats':\n\n filter, lag\n\n\nThe following objects are masked from 'package:base':\n\n intersect, setdiff, setequal, union\n\n\nGenerate the Mock Gene Expression Dataset\n\n# Set random seed for reproducibility\nset.seed(42)\n\n# Number of genes and samples\nnum_genes <- 10\nnum_samples <- 5\n\n# Generate gene names and sample names\ngenes <- paste0(\"Gene_\", 1:num_genes)\nsamples <- paste0(\"Sample_\", 1:num_samples)\n\n# Generate random expression levels\nexpression_data <- matrix(rnorm(num_genes * num_samples), nrow = num_genes, ncol = num_samples)\ncolnames(expression_data) <- samples\nrownames(expression_data) <- genes\n\n# Convert to data frame\ndf_expression <- as.data.frame(expression_data)\n\n# Display the first few rows of the dataset\nhead(df_expression)\n\n Sample_1 Sample_2 Sample_3 Sample_4 Sample_5\nGene_1 1.3709584 1.3048697 -0.3066386 0.4554501 0.2059986\nGene_2 -0.5646982 2.2866454 -1.7813084 0.7048373 -0.3610573\nGene_3 0.3631284 -1.3888607 -0.1719174 1.0351035 0.7581632\nGene_4 0.6328626 -0.2787888 1.2146747 -0.6089264 -0.7267048\nGene_5 0.4042683 -0.1333213 1.8951935 0.5049551 -1.3682810\nGene_6 -0.1061245 0.6359504 -0.4304691 -1.7170087 0.4328180\n\n\nVisualization Part 2: Advanced Visualization Techniques\n\nDensity Plot A density plot shows how the data is spread out, highlighting where values are concentrated.\n\n\ndf_melted <- melt(df_expression, variable.name = \"Sample\", value.name = \"Expression\")\n\nNo id variables; using all as measure variables\n\n# Create the density plot\nggplot(df_melted, aes(x = Expression)) +\n geom_density(fill = \"blue\", alpha = 0.5) + # transparency\n labs(title = \"Density Plot of Gene Expression Levels\",\n x = \"Expression Level\",\n y = \"Density\") +\n theme_minimal()\n\n\n\n\n\n\n\n\n\nViolin Plot: A violin plot is a data visualization that combines a box plot and a kernel density plot to show the distribution, probability density, and variability of data across different categories.\n\n\n# Melt the data frame for ggplot2\ndf_melted <- melt(df_expression, variable.name = \"Sample\", value.name = \"Expression\")\n\nNo id variables; using all as measure variables\n\n# Create the violin plot with colors\nggplot(df_melted, aes(x = Sample, y = Expression, fill = Sample)) +\n geom_violin(trim = FALSE) +\n labs(title = \"Violin Plot of Gene Expression Levels\",\n x = \"Sample\",\n y = \"Expression Level\") +\n theme_minimal() +\n scale_fill_brewer(palette = \"Set3\")\n\n\n\n\n\n\n\n\n\nDendrogram: A dendrogram is a tree-like diagram that displays the arrangement of clusters formed by hierarchical clustering, showing the relationships and distances between data points.\n\n\n# Generate the hierarchical clustering\nhc <- hclust(dist(df_expression), method = \"ward.D2\")\n\n# Create the dendrogram\ndend <- as.dendrogram(hc)\nplot(dend, main = \"Dendrogram\", xlab = \"Genes\", ylab = \"Distance\")\n\n\n\n\n\n\n\n\n\nHeatmap + Dendrogram Heatmaps are useful to visualize matrix-like data, such as gene expression data\n\n\n# Create the heatmap\npheatmap(df_expression, scale = \"row\", main = \"Heatmap of Gene Expression\")\n\n\n\n\n\n\n\n\n\nLoad the iris dataset and prepare it for visualization:\n\n# Load the iris dataset\ndata(\"iris\")\n\n# Display the first few rows of the dataset\nhead(iris)\n\n Sepal.Length Sepal.Width Petal.Length Petal.Width Species\n1 5.1 3.5 1.4 0.2 setosa\n2 4.9 3.0 1.4 0.2 setosa\n3 4.7 3.2 1.3 0.2 setosa\n4 4.6 3.1 1.5 0.2 setosa\n5 5.0 3.6 1.4 0.2 setosa\n6 5.4 3.9 1.7 0.4 setosa\n\nsummary(iris)\n\n Sepal.Length Sepal.Width Petal.Length Petal.Width \n Min. :4.300 Min. :2.000 Min. :1.000 Min. :0.100 \n 1st Qu.:5.100 1st Qu.:2.800 1st Qu.:1.600 1st Qu.:0.300 \n Median :5.800 Median :3.000 Median :4.350 Median :1.300 \n Mean :5.843 Mean :3.057 Mean :3.758 Mean :1.199 \n 3rd Qu.:6.400 3rd Qu.:3.300 3rd Qu.:5.100 3rd Qu.:1.800 \n Max. :7.900 Max. :4.400 Max. :6.900 Max. :2.500 \n Species \n setosa :50 \n versicolor:50 \n virginica :50 \n \n \n \n\n\n\nDensity Plot\n\n\n# Melt the data frame for ggplot2\ndf_melted <- melt(iris, id.vars = \"Species\", variable.name = \"Measurement\", value.name = \"Value\")\n\n# Create the density plot with facets for each species\nggplot(df_melted, aes(x = Value, fill = Measurement)) +\n geom_density(alpha = 0.5) + # transparency\n labs(title = \"Density Plot of Iris Measurements by Species\",\n x = \"Value\",\n y = \"Density\") +\n theme_minimal() +\n facet_wrap(~ Species)\n\n\n\n\n\n\n\n\n\nDensity Plot\n\n\n# Melt the data frame for ggplot2\ndf_melted <- melt(iris, id.vars = \"Species\", variable.name = \"Measurement\", value.name = \"Value\")\n\n# Create the violin plot with colors\nggplot(df_melted, aes(x = Measurement, y = Value, fill = Species)) +\n geom_violin(trim = FALSE) +\n labs(title = \"Violin Plot of Iris Measurements\",\n x = \"Measurement\",\n y = \"Value\") +\n theme_minimal() +\n facet_wrap(~ Measurement, scales = \"free\")\n\n\n\n\n\n\n\n\n\nDendogram\n\n\n# Remove the Species column for clustering\niris_no_species <- iris[, -5]\n\n# Compute the correlation matrix\ncor_matrix <- cor(iris_no_species)\ncor_matrix\n\n Sepal.Length Sepal.Width Petal.Length Petal.Width\nSepal.Length 1.0000000 -0.1175698 0.8717538 0.8179411\nSepal.Width -0.1175698 1.0000000 -0.4284401 -0.3661259\nPetal.Length 0.8717538 -0.4284401 1.0000000 0.9628654\nPetal.Width 0.8179411 -0.3661259 0.9628654 1.0000000\n\n# Perform hierarchical clustering on the correlation matrix\nhc <- hclust(as.dist(1 - cor_matrix), method = \"ward.D2\")\n\n# Create the dendrogram\ndend <- as.dendrogram(hc)\n\n# Plot the dendrogram\nplot(dend, main = \"Dendrogram of Iris Attributes\", xlab = \"Attributes\", ylab = \"Distance\")\n\n\n\n\n\n\n\n\n\n# Remove the Species column for heatmap plotting\niris_data <- iris[, -5]\n\n# Create the heatmap with a simplified color scale\npheatmap(as.matrix(iris_data), \n main = \"Heatmap of Iris Measurements\", \n cluster_rows = TRUE, cluster_cols = TRUE, \n show_rownames = FALSE,\n color = colorRampPalette(c(\"blue\", \"white\", \"red\"))(50))\n\n\n\n\n\n\n\n\n—————————————Assignment 2: Part 2——————————————————–\nDr. Smith is studying the famous iris dataset to understand the differences in flower measurements across three species: setosa, versicolor, and virginica. Help Dr. Smith visualize and interpret the data to identify distinguishing features of each species.\n\nDensity Plot Analysis: Create a density plot to visualize the distribution of sepal length measurements across the three iris species. Identify which species have similar or distinct sepal length distributions.\n\n\n# Solution a\n\n\n# Hint: Look for peaks in the density plots to see which species have similar or distinct sepal length distributions.\n\n\nViolin Plot Analysis: Use a violin plot to compare the distribution and density of petal widths across the three iris species. Highlight which species have the widest and narrowest petals.\n\n\n# Solution b\n\n\n# Hint: Examine the width and shape of the violins to understand the distribution and density of petal widths across species.\\"
},
{
"objectID": "stat.html#statistical-approach",
"href": "stat.html#statistical-approach",
"title": "DAiR Workshop 2024",
"section": "Statistical Approach",
"text": "Statistical Approach\nThe three main categories in statistical modeling:\n\nFrequentist\n\nApproach to Probability: Uses the frequency or long-run proportion of events to describe probabilities.\nOften considered more objective, suited for analyzing experiments.\nEmphasizes rigorous, formal mathematical methods for analyzing and interpreting data.\nIncludes p-values and confidence intervals.\n\nBayesian\n\nBayesian statistics is an approach to data analysis and parameter estimation based on Bayes’ theorem:\n\\[\nP(A∣B)=P(B∣A)P(A)⋅P(B)\n\\]\nwhere 𝐴 and 𝐵 are events and 𝑃(𝐵)≠0\nAllows for the incorporation of prior knowledge and can be updated as new evidence becomes available.\nMore adaptable, suited for situations requiring subjective information or updating predictions with new data.\nAlso emphasizes rigorous mathematical methods, similar to the frequentist.\n\nMachine learning:\n\nDevelops algorithms and computational tools to automatically identify patterns in data and make predictions based on those patterns.\nEmphasizes practical, data-driven approaches where methods are evaluated based on their predictive performance on test datasets.\nLess emphasis on theoretical properties compared to statistical inference; focuses more on empirical performance and scalability.\n\n\nxij denotes the j-th feature of the i-th observation.\n\n\n\n\n\n\nFunction\nDescription\n\n\n\n\nabs(x)\nComputes the absolute value |x|.\n\n\nsqrt(x)\nComputes the square root of x.\n\n\nlog(x)\nComputes the logarithm of x with the natural number e as the base.\n\n\nlog(x, base = a)\nComputes the logarithm of x with the number a as the base.\n\n\na^x\nComputes a^x.\n\n\nexp(x)\nComputes e^x.\n\n\nsin(x)\nComputes sin(x).\n\n\nsum(x)\nWhen x is a vector x = (x1, x2, x3, ..., xn), computes the sum of the elements of x: sum(x) = sum(i=1 to n) xi.\n\n\nprod(x)\nWhen x is a vector x = (x1, x2, x3, ..., xn), computes the product of the elements of x: prod(x) = prod(i=1 to n) xi.\n\n\npi\nA built-in variable with value π, the ratio of the circumference of a circle to its diameter.\n\n\nx %% a\nComputes x modulo a.\n\n\nfactorial(x)\nComputes x!.\n\n\nchoose(n, k)\nComputes n choose k (binomial coefficient).\n\n\n\n\n\n\n\n\n\n\nPlease enable JavaScript to experience the dynamic code cell content on this page.\n\n\nPlease enable JavaScript to experience the dynamic code cell content on this page.",
"crumbs": [
"Home",
"Statistics in R"
]
},
{
"objectID": "Statistics.html",
"href": "Statistics.html",
"title": "R Notebook",
"section": "",
"text": "#install.packages(\"palmerpenguins\")\nlibrary(palmerpenguins)\n?penguins\n\n\nstr(penguins)\n\ntibble [344 × 8] (S3: tbl_df/tbl/data.frame)\n $ species : Factor w/ 3 levels \"Adelie\",\"Chinstrap\",..: 1 1 1 1 1 1 1 1 1 1 ...\n $ island : Factor w/ 3 levels \"Biscoe\",\"Dream\",..: 3 3 3 3 3 3 3 3 3 3 ...\n $ bill_length_mm : num [1:344] 39.1 39.5 40.3 NA 36.7 39.3 38.9 39.2 34.1 42 ...\n $ bill_depth_mm : num [1:344] 18.7 17.4 18 NA 19.3 20.6 17.8 19.6 18.1 20.2 ...\n $ flipper_length_mm: int [1:344] 181 186 195 NA 193 190 181 195 193 190 ...\n $ body_mass_g : int [1:344] 3750 3800 3250 NA 3450 3650 3625 4675 3475 4250 ...\n $ sex : Factor w/ 2 levels \"female\",\"male\": 2 1 1 NA 1 2 1 2 NA NA ...\n $ year : int [1:344] 2007 2007 2007 2007 2007 2007 2007 2007 2007 2007 ...\n\n\n\ntable(penguins$species)\n\n\n Adelie Chinstrap Gentoo \n 152 68 124 \n\n\n\nlibrary(dplyr)\n\nWarning: package 'dplyr' was built under R version 4.3.2\n\n\n\nAttaching package: 'dplyr'\n\n\nThe following objects are masked from 'package:stats':\n\n filter, lag\n\n\nThe following objects are masked from 'package:base':\n\n intersect, setdiff, setequal, union\n\npenguins |> select(species) |> table()\n\nspecies\n Adelie Chinstrap Gentoo \n 152 68 124 \n\n\n\nlibrary(gtsummary)\n\n#BlackLivesMatter\n\ntbl_summary(penguins[,\"species\"])\n\n\n\n\n\n\n\n\n\n\n\n\nCharacteristic\nN = 3441\n\n\n\n\nspecies\n\n\n\n\n Adelie\n152 (44%)\n\n\n Chinstrap\n68 (20%)\n\n\n Gentoo\n124 (36%)\n\n\n\n1 n (%)\n\n\n\n\n\n\n\n\n\n\npenguins |>\nselect(species) |>\ntbl_summary()\n\n\n\n\n\n\n\n\n\n\n\n\nCharacteristic\nN = 3441\n\n\n\n\nspecies\n\n\n\n\n Adelie\n152 (44%)\n\n\n Chinstrap\n68 (20%)\n\n\n Gentoo\n124 (36%)\n\n\n\n1 n (%)\n\n\n\n\n\n\n\n\n\n\nlibrary(flextable)\n\n\nAttaching package: 'flextable'\n\n\nThe following objects are masked from 'package:gtsummary':\n\n as_flextable, continuous_summary\n\n\n\npenguins |>\nselect(species) |>\ntbl_summary() |>\nas_flex_table() |> # Convert the table to a format that can be exported\nsave_as_docx(path = \"~/Documents/DAiR/DAiR_2024_II/my_table.docx\")\n\n\nlibrary(ivo.table)\n\n\npenguins |>\nselect(species) |>\nivo_table()\n\nspeciesAdelieChinstrapGentoo15268124\n\n\n\nftable(penguins$species,\npenguins$island)\n\n Biscoe Dream Torgersen\n \nAdelie 44 56 52\nChinstrap 0 68 0\nGentoo 124 0 0\n\n\n\nlibrary(ivo.table)\npenguins |> select(species, island) |>\nivo_table()\n\nspeciesislandAdelieChinstrapGentooBiscoe440124Dream56680Torgersen5200\n\n\n\npenguins |> select(species, island) |>\nivo_table(color = \"darkred\",\nfont = \"Garamond\",\npercent_by = \"tot\") |>\nsave_as_docx(path = \"~/Documents/DAiR/DAiR_2024_II/penguins.docx\")\n\n\npenguins |> select(species, island) |>\nivo_table(highlight_cols = 3,highlight_rows = 2)\n\nspeciesislandAdelieChinstrapGentooBiscoe440124Dream56680Torgersen5200\n\n\n\ntbl_summary(penguins[,c(\"species\",\"island\")],\nby = species)\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nCharacteristic\nAdelie, N = 1521\nChinstrap, N = 681\nGentoo, N = 1241\n\n\n\n\nisland\n\n\n\n\n\n\n\n\n Biscoe\n44 (29%)\n0 (0%)\n124 (100%)\n\n\n Dream\n56 (37%)\n68 (100%)\n0 (0%)\n\n\n Torgersen\n52 (34%)\n0 (0%)\n0 (0%)\n\n\n\n1 n (%)\n\n\n\n\n\n\n\n\n\n\n# A three-way table:\npenguins |> select(sex, species, island) |>\nivo_table()\n\nsexspeciesislandfemalemale(Missing)AdelieBiscoe22220Dream27281Torgersen24235ChinstrapBiscoe000Dream34340Torgersen000GentooBiscoe58615Dream000Torgersen000\n\n# Exclude missing values:\npenguins |> select(sex, species, island) |>\nivo_table(exclude_missing = TRUE)\n\nsexspeciesislandfemalemaleNAAdelieBiscoe22220Dream27281Torgersen24235ChinstrapBiscoe000Dream34340Torgersen000GentooBiscoe58615Dream000Torgersen000\n\n# A four-way table:\npenguins |> select(sex, species, island, year) |>\nivo_table()\n\nsexspeciesislandyearfemalemale(Missing)AdelieBiscoe200755020089902009880Dream200791012008880200910100Torgersen200787520088802009880ChinstrapBiscoe200700020080002009000Dream2007131302008990200912120Torgersen200700020080002009000GentooBiscoe200716171200822231200920213Dream200700020080002009000Torgersen200700020080002009000"
},
{
"objectID": "stat.html#section",
"href": "stat.html#section",
"title": "DAiR Workshop 2024",
"section": "",
"text": "xij denotes the j-th feature of the i-th observation.\n\n\n\n\n\n\nFunction\nDescription\n\n\n\n\nabs(x)\nComputes the absolute value |x|.\n\n\nsqrt(x)\nComputes the square root of x.\n\n\nlog(x)\nComputes the logarithm of x with the natural number e as the base.\n\n\nlog(x, base = a)\nComputes the logarithm of x with the number a as the base.\n\n\na^x\nComputes a^x.\n\n\nexp(x)\nComputes e^x.\n\n\nsin(x)\nComputes sin(x).\n\n\nsum(x)\nWhen x is a vector x = (x1, x2, x3, ..., xn), computes the sum of the elements of x: sum(x) = sum(i=1 to n) xi.\n\n\nprod(x)\nWhen x is a vector x = (x1, x2, x3, ..., xn), computes the product of the elements of x: prod(x) = prod(i=1 to n) xi.\n\n\npi\nA built-in variable with value π, the ratio of the circumference of a circle to its diameter.\n\n\nx %% a\nComputes x modulo a.\n\n\nfactorial(x)\nComputes x!.\n\n\nchoose(n, k)\nComputes n choose k (binomial coefficient).\n\n\n\n\n\n\n\n\n\n\nPlease enable JavaScript to experience the dynamic code cell content on this page.\n\n\nPlease enable JavaScript to experience the dynamic code cell content on this page.",
"crumbs": [
"Home",
"Statistics in R"
]
},
{
"objectID": "stat.html#hypothesis-testing-and-p-values",
"href": "stat.html#hypothesis-testing-and-p-values",
"title": "DAiR Workshop 2024",
"section": "Hypothesis Testing and P-Values",
"text": "Hypothesis Testing and P-Values\n\nStatistical hypothesis testing is used to determine which of two complementary hypotheses is true.\nIn statistics, a hypothesis is a statement about a parameter in a population, such as the population mean value.\n\nExample Structure of a statement:\n“If I [do this to the independent variable], then [this will happen to the dependent variable].”\n\nThe two hypotheses are:\n1- Null Hypothesis (H0): This corresponds to “no effect,” “no difference,” or “no relationship.”\n2- Alternative Hypothesis (H1): This corresponds to “there is an effect,” “there is a difference,” or “there is a relationship.”\nConducting the Hypothesis Test Formulate the Hypotheses:\n1- Null Hypothesis \\((H0): \\triangle=0\\)\n\nThe mean weight of apples in a farm is 150 grams.\n\nNotation: \\(H_0: \\mu = 150\\)\n\n\n2- Alternative Hypothesis \\((H1): \\triangle ≠ 0\\)\n\nThe mean weight of apples in a farm is not 150 grams.\n\nNotation: \\(H_a: \\mu \\neq 150\\)\n\n\n3- One-way Test (One-tailed Test)\n\nA one-way test, or one-tailed test, considers the possibility of an effect in one direction only.\nThis type of test is used when you have a specific direction in which you expect the results to go.\n\nExample: Testing if the mean weight of apples is greater than 150 grams.\nNotation: \\(H_a: \\mu > 150\\)\n\n\n4- Two-way Test (Two-tailed Test)\n\nA two-way test, or two-tailed test, considers the possibility of an effect in both directions.\nThis test is used when you do not have a specific direction for the effect and want to test for any difference.\n\nExample: Testing if the mean weight of apples is different from 150 grams (could be either greater or less).\nNotation: \\(H_a: \\mu \\neq 150\\)\n\n\n5- Select the Significance Level \\((\\alpha)\\):\n\nAlpha (α) is the probability of rejecting the null hypothesis (H0) when the alternative hypothesis (Ha) is true.\nRanges 0 to 1.\nCommon choices for \\(\\alpha\\) are 0.05, 0.01, and 0.10.\n\n4- Calculate the Test Statistic:\n\nDepending on the test, this could be a t-statistic, z-statistic, etc.\n\n5- Determine the P-Value:\n\nThe p-value (frequentist statistics) is the probability of obtaining a test statistic at least as extreme as the one observed, assuming that the null hypothesis is true.\n\\(\\binom{n}{r}=\\frac {n!}{r!(n−r)!}\\)\nIf the p-value is less than or equal to the significance level \\(\\alpha\\), we reject the null hypothesis.\n\nThe purpose of hypothesis testing is to determine which of the two hypotheses to believe in.\nThe null hypothesis won’t be rejected unless there is compelling evidence against it.\nTypes of Errors:\n\nType I Error: Rejecting \\(H0\\) when it is true (false positive). The probability of committing a Type I error is \\(\\alpha\\).\nType II Error: Failing to reject \\(H0\\) when \\(H1\\) is true (false negative).\nLower \\(\\alpha\\) reduces the risk of Type I errors but increases the risk of Type II errors.\n\n\n\nHigher \\(\\alpha\\) increases the risk of Type I errors but decreases the risk of Type II errors.\n\n\nA common choice is to use \\(\\alpha = 0.05\\) as the cut-off, meaning that the null hypothesis is falsely rejected in 5% of all studies where it is, in fact, true, or that 1 study in 20 finds statistical evidence for alternative hypotheses that are false.",
"crumbs": [
"Home",
"Statistics in R"
]
},
{
"objectID": "Scripts/Statistics.html",
"href": "Scripts/Statistics.html",
"title": "R Notebook",
"section": "",
"text": "#install.packages(\"palmerpenguins\")\nlibrary(palmerpenguins)\n?penguins\n\n\nstr(penguins)\n\ntibble [344 × 8] (S3: tbl_df/tbl/data.frame)\n $ species : Factor w/ 3 levels \"Adelie\",\"Chinstrap\",..: 1 1 1 1 1 1 1 1 1 1 ...\n $ island : Factor w/ 3 levels \"Biscoe\",\"Dream\",..: 3 3 3 3 3 3 3 3 3 3 ...\n $ bill_length_mm : num [1:344] 39.1 39.5 40.3 NA 36.7 39.3 38.9 39.2 34.1 42 ...\n $ bill_depth_mm : num [1:344] 18.7 17.4 18 NA 19.3 20.6 17.8 19.6 18.1 20.2 ...\n $ flipper_length_mm: int [1:344] 181 186 195 NA 193 190 181 195 193 190 ...\n $ body_mass_g : int [1:344] 3750 3800 3250 NA 3450 3650 3625 4675 3475 4250 ...\n $ sex : Factor w/ 2 levels \"female\",\"male\": 2 1 1 NA 1 2 1 2 NA NA ...\n $ year : int [1:344] 2007 2007 2007 2007 2007 2007 2007 2007 2007 2007 ...\n\n\n\ntable(penguins$species)\n\n\n Adelie Chinstrap Gentoo \n 152 68 124 \n\n\n\nlibrary(dplyr)\n\nWarning: package 'dplyr' was built under R version 4.3.2\n\n\n\nAttaching package: 'dplyr'\n\n\nThe following objects are masked from 'package:stats':\n\n filter, lag\n\n\nThe following objects are masked from 'package:base':\n\n intersect, setdiff, setequal, union\n\npenguins |> select(species) |> table()\n\nspecies\n Adelie Chinstrap Gentoo \n 152 68 124 \n\n\n\nlibrary(gtsummary)\ntbl_summary(penguins[,\"species\"])\n\n\n\n\n\n\n\n\n\n\n\n\nCharacteristic\nN = 3441\n\n\n\n\nspecies\n\n\n\n\n Adelie\n152 (44%)\n\n\n Chinstrap\n68 (20%)\n\n\n Gentoo\n124 (36%)\n\n\n\n1 n (%)\n\n\n\n\n\n\n\n\n\n\npenguins |>\nselect(species) |>\ntbl_summary()\n\n\n\n\n\n\n\n\n\n\n\n\nCharacteristic\nN = 3441\n\n\n\n\nspecies\n\n\n\n\n Adelie\n152 (44%)\n\n\n Chinstrap\n68 (20%)\n\n\n Gentoo\n124 (36%)\n\n\n\n1 n (%)\n\n\n\n\n\n\n\n\n\n\nlibrary(flextable)\n\n\nAttaching package: 'flextable'\n\n\nThe following objects are masked from 'package:gtsummary':\n\n as_flextable, continuous_summary\n\n\n\npenguins |>\nselect(species) |>\ntbl_summary() |>\nas_flex_table() |> # Convert the table to a format that can be exported\nsave_as_docx(path = \"~/Documents/DAiR/DAiR_2024_II/my_table.docx\")\n\n\nlibrary(ivo.table)\n\n\npenguins |>\nselect(species) |>\nivo_table()\n\nspeciesAdelieChinstrapGentoo15268124\n\n\n\nftable(penguins$species,\npenguins$island)\n\n Biscoe Dream Torgersen\n \nAdelie 44 56 52\nChinstrap 0 68 0\nGentoo 124 0 0\n\n\n\nlibrary(ivo.table)\npenguins |> select(species, island) |>\nivo_table()\n\nspeciesislandAdelieChinstrapGentooBiscoe440124Dream56680Torgersen5200\n\n\n\npenguins |> select(species, island) |>\nivo_table(color = \"darkred\",\nfont = \"Garamond\",\npercent_by = \"tot\") |>\nsave_as_docx(path = \"~/Documents/DAiR/DAiR_2024_II/penguins.docx\")\n\n\npenguins |> select(species, island) |>\nivo_table(highlight_cols = 3,highlight_rows = 2)\n\nspeciesislandAdelieChinstrapGentooBiscoe440124Dream56680Torgersen5200\n\n\n\ntbl_summary(penguins[,c(\"species\",\"island\")],\nby = species)\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nCharacteristic\nAdelie, N = 1521\nChinstrap, N = 681\nGentoo, N = 1241\n\n\n\n\nisland\n\n\n\n\n\n\n\n\n Biscoe\n44 (29%)\n0 (0%)\n124 (100%)\n\n\n Dream\n56 (37%)\n68 (100%)\n0 (0%)\n\n\n Torgersen\n52 (34%)\n0 (0%)\n0 (0%)\n\n\n\n1 n (%)\n\n\n\n\n\n\n\n\n\n\n# A three-way table:\npenguins |> select(sex, species, island) |>\nivo_table()\n\nsexspeciesislandfemalemale(Missing)AdelieBiscoe22220Dream27281Torgersen24235ChinstrapBiscoe000Dream34340Torgersen000GentooBiscoe58615Dream000Torgersen000\n\n# Exclude missing values:\npenguins |> select(sex, species, island) |>\nivo_table(exclude_missing = TRUE)\n\nsexspeciesislandfemalemaleNAAdelieBiscoe22220Dream27281Torgersen24235ChinstrapBiscoe000Dream34340Torgersen000GentooBiscoe58615Dream000Torgersen000\n\n# A four-way table:\npenguins |> select(sex, species, island, year) |>\nivo_table()\n\nsexspeciesislandyearfemalemale(Missing)AdelieBiscoe200755020089902009880Dream200791012008880200910100Torgersen200787520088802009880ChinstrapBiscoe200700020080002009000Dream2007131302008990200912120Torgersen200700020080002009000GentooBiscoe200716171200822231200920213Dream200700020080002009000Torgersen200700020080002009000"
},
{
"objectID": "Scripts/Script_5.html",
"href": "Scripts/Script_5.html",
"title": "Statistics",
"section": "",
"text": "The dataset palmerpenguins::penguins includes multiple size measurement variables that exhibit correlations.\nlibrary(palmerpenguins)\nlibrary(ivo.table)\ndata<-penguins\ndim(data)\n\n[1] 344 8\nlibrary(dplyr)\n\nWarning: package 'dplyr' was built under R version 4.3.2\n\n\n\nAttaching package: 'dplyr'\n\n\nThe following objects are masked from 'package:stats':\n\n filter, lag\n\n\nThe following objects are masked from 'package:base':\n\n intersect, setdiff, setequal, union\nglimpse(data)\n\nRows: 344\nColumns: 8\n$ species <fct> Adelie, Adelie, Adelie, Adelie, Adelie, Adelie, Adel…\n$ island <fct> Torgersen, Torgersen, Torgersen, Torgersen, Torgerse…\n$ bill_length_mm <dbl> 39.1, 39.5, 40.3, NA, 36.7, 39.3, 38.9, 39.2, 34.1, …\n$ bill_depth_mm <dbl> 18.7, 17.4, 18.0, NA, 19.3, 20.6, 17.8, 19.6, 18.1, …\n$ flipper_length_mm <int> 181, 186, 195, NA, 193, 190, 181, 195, 193, 190, 186…\n$ body_mass_g <int> 3750, 3800, 3250, NA, 3450, 3650, 3625, 4675, 3475, …\n$ sex <fct> male, female, female, NA, female, male, female, male…\n$ year <int> 2007, 2007, 2007, 2007, 2007, 2007, 2007, 2007, 2007…\n\nclass(data)\n\n[1] \"tbl_df\" \"tbl\" \"data.frame\"\n\ntypeof(data)\n\n[1] \"list\"\n\nsum(is.na(data))\n\n[1] 19\n\nwhich(is.na(data))\n\n [1] 692 960 1036 1304 1380 1648 1724 1992 2068 2073 2074 2075 2076 2112 2243\n[16] 2283 2321 2333 2336\n\nlibrary(ggplot2)\nggplot(data=penguins) +\n geom_histogram(aes(x=body_mass_g, fill=species))\n\n`stat_bin()` using `bins = 30`. Pick better value with `binwidth`.\n\n\nWarning: Removed 2 rows containing non-finite outside the scale range\n(`stat_bin()`).\ndata[1,]\n\n# A tibble: 1 × 8\n species island bill_length_mm bill_depth_mm flipper_length_mm body_mass_g\n <fct> <fct> <dbl> <dbl> <int> <int>\n1 Adelie Torgersen 39.1 18.7 181 3750\n# ℹ 2 more variables: sex <fct>, year <int>\ndata |> count(species)|>ivo_table()\n\nspeciesnAdelieChinstrapGentoo68010124001152100\napply(data,2,mean)#this code will causing an error.\n\nWarning in mean.default(newX[, i], ...): argument is not numeric or logical:\nreturning NA\nWarning in mean.default(newX[, i], ...): argument is not numeric or logical:\nreturning NA\nWarning in mean.default(newX[, i], ...): argument is not numeric or logical:\nreturning NA\nWarning in mean.default(newX[, i], ...): argument is not numeric or logical:\nreturning NA\nWarning in mean.default(newX[, i], ...): argument is not numeric or logical:\nreturning NA\nWarning in mean.default(newX[, i], ...): argument is not numeric or logical:\nreturning NA\nWarning in mean.default(newX[, i], ...): argument is not numeric or logical:\nreturning NA\nWarning in mean.default(newX[, i], ...): argument is not numeric or logical:\nreturning NA\n\n\n species island bill_length_mm bill_depth_mm \n NA NA NA NA \nflipper_length_mm body_mass_g sex year \n NA NA NA NA\nwhich(is.na(data), arr.ind = TRUE)\n\n row col\n [1,] 4 3\n [2,] 272 3\n [3,] 4 4\n [4,] 272 4\n [5,] 4 5\n [6,] 272 5\n [7,] 4 6\n [8,] 272 6\n [9,] 4 7\n[10,] 9 7\n[11,] 10 7\n[12,] 11 7\n[13,] 12 7\n[14,] 48 7\n[15,] 179 7\n[16,] 219 7\n[17,] 257 7\n[18,] 269 7\n[19,] 272 7\ndim(data)\n\n[1] 344 8\n\nlibrary(tidyr)\n\nWarning: package 'tidyr' was built under R version 4.3.2\n\ndf <- drop_na(data)\ndfII<-na.omit(data)\ndim(df)\n\n[1] 333 8\n\ndim(dfII)\n\n[1] 333 8\nall(colnames(data)%in%colnames(df))\n\n[1] TRUE\n\nall(row_number(data)%in%row_number(df))\n\n[1] FALSE\n# Calculate the mean and standard deviation Gentoo body mass in our data (sometimes base R is more sensible than dplyr)\nmean(df$body_mass_g, na.rm=TRUE)\n\n[1] 4207.057\n\nsd(df$body_mass_g, na.rm=TRUE)\n\n[1] 805.2158\nnumeric_columns <- sapply(df, is.numeric)\nnumeric_columns\n\n species island bill_length_mm bill_depth_mm \n FALSE FALSE TRUE TRUE \nflipper_length_mm body_mass_g sex year \n TRUE TRUE FALSE TRUE \n\nis.vector(numeric_columns)\n\n[1] TRUE\n\nclass(numeric_columns)\n\n[1] \"logical\"\n\ntypeof(numeric_columns)\n\n[1] \"logical\"\napply(df[, numeric_columns], 2, mean, na.rm = TRUE)|> table()\n\n\n17.1648648648649 43.9927927927928 200.966966966967 2008.04204204204 \n 1 1 1 1 \n4207.05705705706 \n 1\nnumeric_columns <- sapply(names(df), function(col) is.numeric(df[[col]]) && !grepl(\"year\", col))#to remove column \"year\", which is numeric but must be excluded from the calculation.\nlapply(df[, numeric_columns], mean)|> as.data.frame()|>ivo_table()\n\nbill_length_mmbill_depth_mmflipper_length_mmbody_mass_g43.992792792792817.1648648648649200.9669669669674207.057057057061\nlibrary(flextable)\nsummary_result <- df |> \n select(3:6) |> # Select the specified columns\n summarise_all(list(min = min, max = max,median=median))\nsummary_result |> as_flextable()\n\nbill_length_mm_minnumeric32.1bill_depth_mm_minnumeric13.1flipper_length_mm_mininteger172body_mass_g_mininteger2,700bill_length_mm_maxnumeric59.6bill_depth_mm_maxnumeric21.5flipper_length_mm_maxinteger231body_mass_g_maxinteger6,300bill_length_mm_mediannumeric44.5bill_depth_mm_mediannumeric17.3\nlibrary(flextable)\nsummary_result <- df |> \n select(3:6) |> # Select the specified columns\n summarise_all(list(min = min, max = max,median=median)) |> as_flextable()|> # Convert the table to a format that can be exported\nsave_as_docx(path = \"~/Documents/DAiR/DAiR_2024_II/min_max.docx\")"
},
{
"objectID": "stat.html#correlation",
"href": "stat.html#correlation",
"title": "DAiR Workshop 2024",
"section": "Correlation",
"text": "Correlation\n\nCorrelation measures how closely related two variables are.\nA positive value close to 1 indicates a strong positive linear relationship (as one variable increases, the other tends to increase).\nA value close to 0 indicates no linear relationship.\nA negative value close to -1 indicates a strong negative linear relationship (as one variable increases, the other tends to decrease).\n\nPearson’s Test: Assumes data follows a normal distribution and calculates linear correlation.\n\n\n\nSpearman’s Test: Does not require normality; evaluates non-linear correlation.\nKendall’s Test: Also does not require normality; assesses non-linear correlation and is more robust. However, it is more complex to compute manually and is less commonly used.\nComparing Tests: Results from different tests cannot be directly compared; Kendall’s correlation coefficients typically range 20-40% lower than Spearman’s.",
"crumbs": [
"Home",
"Statistics in R"
]
},
{
"objectID": "stat.html#t-test",
"href": "stat.html#t-test",
"title": "DAiR Workshop 2024",
"section": "t-Test",
"text": "t-Test\n\nA statistical method used to compare the means of two groups.\nIf your group variable has more than two levels, it’s not appropriate to use a t-test; instead, use an ANOVA (Analysis of Variance).\nTypes of t-test\n\nOne Sample T-test:\n\nCompares the mean of a sample to a known value (population mean).\nUsed when comparing the mean of a sample to a known value (population mean).\n\nPaired T-test (Dependent T-test):\n\nCompares the means of two related groups (e.g., before and after treatment).\nUsed when comparing the means of two related groups (e.g., before and after treatment).\n\nUnpaired T-test (Independent T-test):\n\nCompares the means of two independent groups.\n\nStudent’s T-test:\n\nUsed when the variance in both groups is assumed to be equal.\nAlso known as the Equal Variance T-test or Two Sample T-test.\nUsed when the sample sizes and variances of the two groups are assumed to be equal.\n\n\n\n\nWelch T-test:\n\nUsed when the variance in the two groups is assumed to be unequal.\nAlso known as the Unequal Variance T-test or Welch’s T-test.\nUsed when the sample sizes and variances of the two groups are different.\n\n\n\n\nChi-Square test\n\nTest of Independence\nTest of Association\nIt is a non-parametric test used to determine if there is a relationship between two categorical variables.\n\n\n\nThe null hypothesis states that no relationship exists between the variables (they are independent).\nIt compares categorical variables and cannot be used to compare numerical variables.\nIt indicates whether the two variables are dependent or independent but does not specify the type of relationship between them.\nThere must be a Contingency Table which:\n\nHas at least two rows and two columns (2x2).\nIs used to present categorical data in terms of frequency counts.\n\nTwo Categorical Variables: Each variable should have at least two groups (e.g., Gender with groups Female and Male).\n\n\n\nIndependence of Observations: There should be independence both between and within subjects in the data.\nLarge Sample Size: This ensures the validity of the test results.\n\nExpected Frequencies: Each cell in the contingency table should ideally have an expected frequency of at least 1.\nMajority of Cells: At least 80% of the cells should have expected frequencies of at least 5.\n\n\nCorrelation test\n\nCorrelation tests are used to measure the strength and direction of relationships between variables. Here are the key points:\nCorrelation quantifies whether greater values of one variable correspond to greater values of another variable. It is scaled between +1 and -1:\n\nPositive Correlation: Values increase together.\nNegative Correlation: One value decreases as the other increases.\nZero Correlation: No apparent link between the values.\n\nCorrelation Methods\n\nPearson’s Test: Assumes normal distribution and measures linear correlation between continuous variables.\nSpearman’s Test: Non-parametric test that does not assume normality; measures non-linear correlation, suitable for continuous or ordinal variables.\nKendall’s Test: Non-parametric test similar to Spearman’s, also measures non-linear correlation but less commonly used.\nDifferences Between Pearson’s and Spearman’s Tests\n\n\n\n\nPearson’s Test\nSpearman’s Test\n\n\n\n\nType\nParametric\nNon-parametric\n\n\nRelationship\nLinear\nNon-linear\n\n\nVariables\nContinuous\nContinuous or ordinal\n\n\nSensitivity\nProportional change\nChange not at constant rate\n\n\n\n\nANOVA\n\nANOVA (Analysis of Variance) is a statistical test used to compare the means of three or more groups of data. Here are the key points:\nTypes of ANOVA\n\nOne-way ANOVA\n\nCompares the means of three or more groups based on a single independent variable (or factor).\nRequires at least three observations within each group.\n\nTwo-way ANOVA\n\nCompares the means of three or more groups considering two independent variables (or factors).\nEvaluates how each variable individually and together affect the dependent variable.\n\n\nAssumptions\n\nIndependence: Observations within each sample are independent and identically distributed (iid).\nNormality: Data in each sample follows a normal distribution.\nEqual Variance: Variances across all samples are equal.\n\nInterpretation\n\nNull Hypothesis (H0): Assumes all group means are equal.\nAlternative Hypothesis (H1): States that at least one group mean is different from others.\n\n\nAfter determining that there are differences among the samples, pairwise comparisons must be conducted to identify which specific groups differ from each other.\nAs the number of comparisons increases, the probability of a false positive (Type I error) increases dramatically (e.g., 90% probability with α = 0.05).\nPost-hoc tests address this issue by adjusting the significance level (α) to maintain an overall desired level of significance across multiple comparisons.\nCommon post-hoc tests include:\n\nTukey HSD: Compares all possible pairs of groups to each other.\nDunnett: Compares treatment groups with a control group.\nBonferroni Correction: Divides the desired global α level by the number of comparisons (α’ = α / number of comparisons).\n\n\n\nKruskal-Wallis test\n\nThe Kruskal-Wallis test is utilized to compare three or more groups based on a quantitative variable, extending the Mann-Whitney test, which compares two groups under non-normality assumptions.\nNull Hypothesis (H0): The three penguin species have equal bill lengths.\n\n\n\nAlternative Hypothesis (H1): At least one species differs in bill length from the other two species.\nIt’s important to note that rejecting the null hypothesis does not imply that all species differ in flipper length; it means at least one species differs from the others.\nThe Kruskal-Wallis test requires a quantitative dependent variable (bill length) and a qualitative independent variable (penguin species with at least three levels).\nIt is a nonparametric test, hence it does not assume normality.\nThe observations must be independence groups.\nEquality of variances is not required for comparing groups but is necessary if comparing medians directly.\nIt’s essential to identify which specific group(s) differ from the others using post-hoc tests, also known as multiple pairwise-comparison tests, which conducted after obtaining significant results from the Kruskal-Wallis test.\nCommon post-hoc tests following a significant Kruskal-Wallis test include:\n\nDunn test\nConover test\nNemenyi test\nPairwise Wilcoxon test\n\n\n\n\n\nPlease enable JavaScript to experience the dynamic code cell content on this page.\n\n\nPlease enable JavaScript to experience the dynamic code cell content on this page.",
"crumbs": [
"Home",
"Statistics in R"
]
},
{
"objectID": "stat.html#chi-squared-test",
"href": "stat.html#chi-squared-test",
"title": "DAiR Workshop 2024",
"section": "Chi-squared Test",
"text": "Chi-squared Test\n\nA statistical test used to determine if there is a relationship between two categorical variables.\nNull Hypothesis: Assumes that the variables are independent of each other.\n\n\n\n Statistical Tests Summary\n \n\n\n\nStatistical Tests Summary\n\n\n\n\n\nNumber of Dependent Variables\nNature of Independent Variables\nNature of Dependent Variable(s)*\nTest(s)\nHow to R\n\n\n1\n0 IVs (1 population)\ninterval & normal\none-sample t-test\nR\n\n\n\n\nordinal or interval\none-sample median\nR\n\n\n\n\ncategorical (2 categories)\nbinomial test\nR\n\n\n\n\ncategorical\nChi-square goodness-of-fit\nR\n\n\n1 IV with 2 levels (independent groups)\ninterval & normal\n2 independent sample t-test\nR\n\n\n\n\nordinal or interval\nWilcoxon-Mann Whitney test\nR\n\n\n\n\ncategorical\nChi-square test\nR\n\n\n\n\n\n\nFisher’s exact test\nR\n\n\n1 IV with 2 or more levels (independent groups)\ninterval & normal\none-way ANOVA\nR\n\n\n\n\nordinal or interval\nKruskal Wallis\nR\n\n\n\n\ncategorical\nChi-square test\nR\n\n\n\n1 IV with 2 levels (dependent/matched groups)\ninterval & normal\npaired t-test\nR\n\n\n\n\nordinal or interval\nWilcoxon signed ranks test\nR\n\n\n\n\ncategorical\nMcNemar\nR\n\n\n\n1 IV with 2 or more levels (dependent/matched groups)\ninterval & normal\none-way repeated measures ANOVA\nSAS\nR\n\n\n\nordinal or interval\nFriedman test\nR\n\n\n\n\ncategorical (2 categories)\nrepeated measures logistic regression\nR\n\n\n\n2 or more IVs (independent groups)\ninterval & normal\nfactorial ANOVA\nR\n\n\n\n\nordinal or interval\nordered logistic regression\nR\n\n\n\n\ncategorical (2 categories)\nfactorial logistic regression\nR\n\n\n\n1 interval IV\ninterval & normal\ncorrelation\nR\n\n\n\n\n\nsimple linear regression\nR\n\n\n\n\nordinal or interval\nnon-parametric correlation\nR\n\n\n\n\ncategorical\nsimple logistic regression\nR\n\n\n\n1 or more interval IVs and/or 1 or more categorical IVs\ninterval & normal\nmultiple regression\nR\n\n\n\n\n\nanalysis of covariance\nR\n\n\n\n\ncategorical\nmultiple logistic regression\nR\n\n\n\n\n\ndiscriminant analysis\nR\n\n\n\n2+\n1 IV with 2 or more levels (independent groups)\ninterval & normal\none-way MANOVA\nR\n\n\n2+\ninterval & normal\nmultivariate multiple linear regression\nR\n\n\n\n0\ninterval & normal\nfactor analysis\nR\n\n\n\n2 sets of 2+\n0\ninterval & normal\ncanonical correlation\nR\n\n\n\n\n\n\n\n\n\nPlease enable JavaScript to experience the dynamic code cell content on this page.\n\n\nPlease enable JavaScript to experience the dynamic code cell content on this page.",
"crumbs": [
"Home",
"Statistics in R"
]
},
{
"objectID": "stat.html#classical-statistics",
"href": "stat.html#classical-statistics",
"title": "DAiR Workshop 2024",
"section": "Classical Statistics",
"text": "Classical Statistics\nClassical statistics covers essential topics that are central to data analysis, including:\n\nEstimation: The process of inferring the value of a population parameter based on a sample.\nQuantification of Uncertainty: Assessing the reliability and variability of estimates and predictions.\nHypothesis Testing: Evaluating hypotheses about population parameters based on sample data.\n\nThese topics form the foundation for analyzing data, making decisions, and drawing conclusions from data.\n\nEstimate\n\nA statistic calculated from your data.\nCalled an estimate because it approximates population-level values from sample data. It’s synonym is “Metric.”\n\n\nlibrary(palmerpenguins)\ndata<-penguins\n\n\n\n\n\n\n\nFunction\nDescription\n\n\n\n\nabs(x)\nComputes the absolute value |x|.\n\n\nsqrt(x)\nComputes the square root of x.\n\n\nlog(x)\nComputes the logarithm of x with the natural number e as the base.\n\n\nlog(x, base = a)\nComputes the logarithm of x with the number a as the base.\n\n\na^x\nComputes a^x.\n\n\nexp(x)\nComputes e^x.\n\n\nsin(x)\nComputes sin(x).\n\n\nsum(x)\nWhen x is a vector x = (x1, x2, x3, ..., xn), computes the sum of the elements of x: sum(x) = sum(i=1 to n) xi.\n\n\nprod(x)\nWhen x is a vector x = (x1, x2, x3, ..., xn), computes the product of the elements of x: prod(x) = prod(i=1 to n) xi.\n\n\npi\nA built-in variable with value π, the ratio of the circumference of a circle to its diameter.\n\n\nx %% a\nComputes x modulo a.\n\n\nfactorial(x)\nComputes x!.\n\n\nchoose(n, k)\nComputes n choose k (binomial coefficient).",
"crumbs": [
"Home",
"Statistics in R"
]
},
{
"objectID": "stat.html#types-of-statistical-tests",
"href": "stat.html#types-of-statistical-tests",
"title": "DAiR Workshop 2024",
"section": "Types of Statistical Tests",
"text": "Types of Statistical Tests\n\nParametric: Applicable to normal distributions.\n\nUsed to compare means of groups.\n\nStudent’s t-test\n\n\n\nPaired Student’s t-test\nAnalysis of Variance (ANOVA) Test\nRepeated Measures ANOVA Test\n\n\n\n\nApplied to samples with normally distributed numeric data.\nUtilize the actual values of the variable.\n\nNon-Parametric: Applicable to any distribution.\n\nUsed to compare medians of groups.\n\nMann-Whitney U Test\n\n\n\nWilcoxon Signed-Rank Test\nKruskal-Wallis H Test\nFriedman Test\n\nApplied to samples with non-normally distributed numeric data or ordinal data.\nUtilize the ranks of the values.",
"crumbs": [
"Home",
"Statistics in R"
]
},
{
"objectID": "stat.html#correlation-test",
"href": "stat.html#correlation-test",
"title": "DAiR Workshop 2024",
"section": "Correlation test",
"text": "Correlation test\n\nCorrelation measures how closely related two variables are. It is suitable to studying the association between two variables.\nA positive value close to 1 indicates a strong positive linear relationship (as one variable increases, the other tends to increase).\nA value close to 0 indicates no linear relationship.\nA negative value close to -1 indicates a strong negative linear relationship (as one variable increases, the other tends to decrease).\n\nPearson’s Test: Assumes data follows a normal distribution and calculates linear correlation.\n\n\n\nSpearman’s Test: Does not require normality; evaluates non-linear correlation.\nKendall’s Test: Also does not require normality; assesses non-linear correlation and is more robust. However, it is more complex to compute manually and is less commonly used.\nCHi-Square test\n\nA statistical test used to determine if there is a relationship between two categorical variables.\nNull Hypothesis: Assumes that the variables are independent of each other.\n\nComparing Tests: Results from different tests cannot be directly compared; Kendall’s correlation coefficients typically range 20-40% lower than Spearman’s.\n\n\n\nBivariate Analysis\n\nInvolves two variables.\nAims to determine the relationship or association between the two variables.\n\nIndependent (Unpaired) Data:\n\nObservations in each sample are not related.\nNo relationship exists between the subjects in each sample.\nCharacteristics:\n\nSubjects in the first group cannot also be in the second group.\nNo subject in either group can influence subjects in the other group.\nNo group can influence the other group.\n\n\nDependent (Paired) Data:\n\nPaired samples include:\n\nPre-test/post-test samples (a variable is measured before and after an intervention).\nCross-over trials.\nMatched samples.\nWhen a variable is measured twice or more on the same individual.\n\n\n\n\n\n\nMultivariate Analysis\n\nInvolves more than two variables.\nAims to understand how multiple factors simultaneously impact an outcome.\nUses regression models to quantify the effect of each variable while controlling for the others.",
"crumbs": [
"Home",
"Statistics in R"
]
},
{
"objectID": "Exercises/Exercise_6.html",
"href": "Exercises/Exercise_6.html",
"title": "Exercise_5",
"section": "",
"text": "Calculating Correlation Between Flipper Length and Body Mass\nObjective: We will calculate correlations between Flipper Length and Body Mass using Pearson, Kendall, and Spearman methods in R.\nTasks:\n\nLoad the dataset.\nCalculate the correlation between Flipper Length (flipper_length_mm) and Body Mass (body_mass_g) using Pearson, Kendall, and Spearman methods.\nPrint and display the correlation coefficients for each method.\n\nHints:\n\nUse cor() function in R with the method argument set to \"pearson\", \"kendall\", and \"spearman\" for calculating correlations.\nSubset or filter the dataset to include relevant columns (flipper_length_mm and body_mass_g)."
},
{
"objectID": "Exercises/Exercise_5.html",
"href": "Exercises/Exercise_5.html",
"title": "Exercise_5",
"section": "",
"text": "Objective: We will analyze body mass data of Gentoo penguins using R, perform normality tests, compare body masses between males and females, interpret the results, and visualize the data.\nTasks:\n\nLoad the dataset and filter it to include only Gentoo penguins (species == \"Gentoo\").\nPerform a Shapiro-Wilk test (shapiro.test()) to check the normality of body mass (body_mass_g) for Gentoo penguins.\nSeparately, perform Shapiro-Wilk tests for body mass (bill_length_mm) of male and female Gentoo penguins.\nInterpret the results of the normality tests.\nVisualize body mass distributions for Gentoo penguins, showing comparisons between males and females using appropriate plots.\n\nHints:\n\nUse shapiro.test() for normality tests.\nUse subsetting or filtering (subset() or dplyr::filter()) to select Gentoo penguins.\nUse ggplot2 or base R plots for visualization."
},
{
"objectID": "Exercises/Exercise_5.html#analyzing-body-mass-data-of-gentoo-penguins",
"href": "Exercises/Exercise_5.html#analyzing-body-mass-data-of-gentoo-penguins",
"title": "Exercise_5",
"section": "",
"text": "Objective: We will analyze body mass data of Gentoo penguins using R, perform normality tests, compare body masses between males and females, interpret the results, and visualize the data.\nTasks:\n\nLoad the dataset and filter it to include only Gentoo penguins (species == \"Gentoo\").\nPerform a Shapiro-Wilk test (shapiro.test()) to check the normality of body mass (body_mass_g) for Gentoo penguins.\nSeparately, perform Shapiro-Wilk tests for body mass (bill_length_mm) of male and female Gentoo penguins.\nInterpret the results of the normality tests.\nVisualize body mass distributions for Gentoo penguins, showing comparisons between males and females using appropriate plots.\n\nHints:\n\nUse shapiro.test() for normality tests.\nUse subsetting or filtering (subset() or dplyr::filter()) to select Gentoo penguins.\nUse ggplot2 or base R plots for visualization."
},
{
"objectID": "Scripts/Script_5.html#to-visualize-the-distribution-of-bill_length_mm",
"href": "Scripts/Script_5.html#to-visualize-the-distribution-of-bill_length_mm",
"title": "Statistics",
"section": "To visualize the distribution of bill_length_mm:",
"text": "To visualize the distribution of bill_length_mm:\n\nfreq<-table(bill_length)\nfreq\n\nbill_length\n tiny small moderate large \n 86 81 83 83 \n\nhist<-hist(df$bill_length_mm, \n breaks = c(32.1,39.5,44.5,48.6,max(df$bill_length_mm)),\n probability=TRUE,\n col = \"skyblue\", # Color of bars\n border = \"black\", # Color of bar borders\n xlab = \"Bill Length (mm)\", # X-axis label\n ylab = \"Frequency\", # Y-axis label\n main = \"Histogram of Bill Lengths\", # Title of the plot\n xlim = c(30, 60),\n ylim = c(0,.08)\n)\nhist\n\n$breaks\n[1] 32.1 39.5 44.5 48.6 59.6\n\n$counts\n[1] 86 81 83 83\n\n$density\n[1] 0.03489976 0.04864865 0.06079250 0.02265902\n\n$mids\n[1] 35.80 42.00 46.55 54.10\n\n$xname\n[1] \"df$bill_length_mm\"\n\n$equidist\n[1] FALSE\n\nattr(,\"class\")\n[1] \"histogram\"\n\nrug(jitter(df$bill_length_mm), side = 1, col = \"red\")\ntext(hist$mids, hist$density + 0.003, labels = hist$counts, col = \"black\")\n\n\n\n\n\n\n\n\nBy setting probability=TRUE, the histogram displays the relative frequencies, making the total area under the histogram equal to 1. This means that the height of each bar represents the relative frequency (or proportion) of data points within each bin, effectively normalizing the histogram. This approach aligns the histogram with the concept of a probability density function, allowing for a better understanding of the distribution in terms of probabilities.\n\nbp<- boxplot(df$bill_length_mm,horizontal=TRUE,main = \"Boxplot of Bill Length\", xlab = \"Bill Length (mm)\")\nbp$stats\n\n [,1]\n[1,] 32.1\n[2,] 39.5\n[3,] 44.5\n[4,] 48.6\n[5,] 59.6\n\n# Add annotations using the statistics from bp$stats\ntext(bp$stats[1, 1], 1.2, labels = paste(\"Min:\", round(bp$stats[1, 1], 2)), pos = 3, cex = 0.5)\ntext(bp$stats[2, 1], 1.2, labels = paste(\"Q1:\", round(bp$stats[2, 1], 2)), pos = 3, cex = 0.5)\ntext(bp$stats[3, 1], 1.2, labels = paste(\"Median:\", round(bp$stats[3, 1], 2)), pos = 3, cex = 0.5)\ntext(bp$stats[4, 1], 1.2, labels = paste(\"Q3:\", round(bp$stats[4, 1], 2)), pos = 3, cex = 0.5)\ntext(bp$stats[5, 1], 1.2, labels = paste(\"Max:\", round(bp$stats[5, 1], 2)), pos = 3, cex = 0.5)\n\n\n\n\n\n\n\n\n\nfor (col in names(numeric_columns)[numeric_columns]) {\n bp <- boxplot(df[[col]], horizontal = TRUE, main = paste(\"Boxplot of\", col), xlab = col)\n stats <- bp$stats\n \n # Add annotations using the statistics from bp$stats\n text(stats[1, 1], 1.2, labels = paste(\"Min:\", round(stats[1, 1], 2)), pos = 3, cex = 0.5)\n text(stats[2, 1], 1.2, labels = paste(\"Q1:\", round(stats[2, 1], 2)), pos = 3, cex = 0.5)\n text(stats[3, 1], 1.2, labels = paste(\"Median:\", round(stats[3, 1], 2)), pos = 3, cex = 0.5)\n text(stats[4, 1], 1.2, labels = paste(\"Q3:\", round(stats[4, 1], 2)), pos = 3, cex = 0.5)\n text(stats[5, 1], 1.2, labels = paste(\"Max:\", round(stats[5, 1], 2)), pos = 3, cex = 0.5)\n}\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nmale_Ge <- df %>%\n filter(species == 'Gentoo' & sex == 'male')\n\nfemale_Ge <- df %>%\n filter(species == 'Gentoo' & sex == 'female')\n\nmale<- male_Ge[,6] #select body mass\nmale<- as.numeric(unlist(male)) #eliminate list\n\nfemale<- female_Ge[,6]\nfemale<- as.numeric(unlist(female)) #eliminate list\npar(mfrow=c(1,2))\nboxplot(male, main =\"male\", col =\"blue\")\nboxplot(female, main = \"female\", col =\"red\")\n\n\n\n\n\n\n\n\n\n# Convert selected columns to matrix\nmat <- as.matrix(df[, numeric_columns])\n# Compute row-wise proportions\npropR<- prop.table(mat, 1)|>as.data.frame()\nsum(propR$bill_length_mm)\n\n[1] 3.341828\n\n# Compute column-wise proportions\npropC<- prop.table(mat, 2)|>as.data.frame()\nsum(propC$bill_length_mm)\n\n[1] 1\n\n\n\nboxplot(scale(mat))\n\n\n\n\n\n\n\n\n\nlibrary(ggplot2)\n# Plotting histograms for all numeric columns\nplot_list <- lapply(names(df)[sapply(df, is.numeric)], function(col) {\n ggplot(df, aes_string(x = col)) +\n geom_histogram(binwidth = .75, fill = \"blue\", color = \"black\") +\n labs(title = paste(\"Distribution of\", col), x = col, y = \"Frequency\") +\n theme_minimal()\n})\n\nWarning: `aes_string()` was deprecated in ggplot2 3.0.0.\nℹ Please use tidy evaluation idioms with `aes()`.\nℹ See also `vignette(\"ggplot2-in-packages\")` for more information.\n\n# Arrange plots in a grid using gridExtra package\nlibrary(gridExtra)\n\n\nAttaching package: 'gridExtra'\n\n\nThe following object is masked from 'package:dplyr':\n\n combine\n\ngrid.arrange(grobs = plot_list, ncol = 2) \n\n\n\n\n\n\n\n\n\nggplot(df, aes(x = island, y = sex, fill = sex)) +\n geom_violin(trim = FALSE) +\n labs(title = \"Comparison of Bill Depth by Island\", x = \"Island\", y = \"Bill Depth (mm)\")\n\n\n\n\n\n\n\n\n\nggplot(df, aes(x = bill_length_mm, fill = sex)) +\n geom_density(alpha = 0.5) +\n labs(title = \"Density of bill_length_mm by Sex\", x = \"bill_length(mm)\", y = \"Density\") +\n scale_fill_manual(values = c(\"blue\", \"red\")) \n\n\n\n\n\n\n\n\n\nggplot(df, aes(x = bill_length_mm, fill = species)) +\n geom_density(alpha = 0.5) +\n labs(title = \"Density of bill_depth_mm by Sex\", x = \"bill_depth(mm)\", y = \"Density\") +\n scale_fill_manual(values = c(\"blue\", \"red\",\"green\")) \n\n\n\n\n\n\n\n\n\nggplot(df, aes(x = bill_length_mm, fill = species)) +\n geom_density(alpha = 0.5) +\n geom_density(aes(x = bill_depth_mm, fill = species), alpha = 0.5, color = \"black\", linetype = \"dashed\") +\n labs(title = \"Density of bill_length_mm and flipper_length_mm by Species\", x = \"Length (mm)\", y = \"Density\") +\n scale_fill_manual(values = c(\"blue\", \"red\", \"green\"))\n\n\n\n\n\n\n\n\n\nggplot(df, aes(x = body_mass_g, fill = species)) +\n geom_density(alpha = 0.5) +\n labs(title = \"Density of Body Mass by Sex\", x = \"Body Mass (g)\", y = \"Density\") +\n scale_fill_manual(values = c(\"blue\", \"red\",\"green\")) # Optional: customizing fill colors\n\n\n\n\n\n\n\n\n\npar(mfrow = c(1, 2)) # 2 graphs per page\n# Create the violin plot\nviolin_plot <- ggplot(df, aes(x = species, y = bill_length_mm, fill = species)) +\n geom_violin() +\n theme_minimal() +\n labs(title = \"Violin Plot of Bill Length by Species\",\n x = \"Species\",\n y = \"Bill Length (mm)\")\n# Create a density plot of bill length\ndensity_plot <- ggplot(df, aes(x = bill_length_mm, fill = species, color = species)) +\n geom_density(alpha = 0.5) +\n theme_minimal() +\n labs(title = \"Density Plot of Bill Length by Species\",\n x = \"Bill Length (mm)\",\n y = \"Density\")\n\n# Arrange the plots in a 1x3 grid\ngrid.arrange(violin_plot, density_plot, ncol = 2)\n\n\n\n\n\n\n\n\n\nunique(df$species)\n\n[1] Adelie Gentoo Chinstrap\nLevels: Adelie Chinstrap Gentoo\n\ngentoo = df %>% \n filter(species==\"Gentoo\") \nggplot(data=gentoo) +\n geom_histogram(aes(x=body_mass_g),fill=\"green\")+\n labs(title = \"Histogram of Body Mass in Gentoo\", x = \"Body Mass (g)\", y = \"count\") \n\n`stat_bin()` using `bins = 30`. Pick better value with `binwidth`.\n\n\n\n\n\n\n\n\n\n\n# Check normality assumption with a qqplot:\nnorm_check<-qqnorm(gentoo$bill_length_mm, pch=10,col=\"blue\")\nnorm_check<-qqline(gentoo$bill_length_mm,col=\"red\",lwd=1)\n\n\n\n\n\n\n\nnorm_check\n\nNULL\n\nlibrary(\"car\")\n\nLoading required package: carData\n\n\n\nAttaching package: 'car'\n\n\nThe following object is masked from 'package:dplyr':\n\n recode\n\nqqnormplot<- qqPlot(gentoo$bill_length_mm)\n\n\n\n\n\n\n\nqqnormplot\n\n[1] 33 100\n\nlibrary(performance)\ncheck_normality(gentoo$bill_length_mm,sample.size=length(gentoo$bill_length_mm), main = \"Y\")\n\nWarning: Non-normality of raw detected (p = 0.020).\n\nggplot(gentoo, aes(x = bill_length_mm)) +\n geom_histogram(binwidth = 1, color = \"black\", fill = \"lightblue\") +\n labs(title = \"Histogram of Bill Length (mm)\", x = \"Bill Length (mm)\", y = \"Frequency\")\n\n\n\n\n\n\n\n\nThe rnorm() function in R generates a vector of random numbers sampled from a normal distribution. It requires three main arguments to define the characteristics of the distribution:n ,mean ,sd\n\n#Example of Noemal distributed data\nresults = c();\nmu = 0; sigma = 1\nfor(i in 1:500) {\n X = rnorm(100,mu,sigma) # generate random data\n results[i] = (mean(X) - mu)/(sigma/sqrt(100))\n}\nhis_X <- hist(results,prob=T,xlim = c(-3,3))\nhis_X <- curve(dnorm(x, 0, 1), add = TRUE, col = \"blue\", lwd = 2)\n\n\n\n\n\n\n\nhis_X\n\n$x\n [1] -3.00 -2.94 -2.88 -2.82 -2.76 -2.70 -2.64 -2.58 -2.52 -2.46 -2.40 -2.34\n [13] -2.28 -2.22 -2.16 -2.10 -2.04 -1.98 -1.92 -1.86 -1.80 -1.74 -1.68 -1.62\n [25] -1.56 -1.50 -1.44 -1.38 -1.32 -1.26 -1.20 -1.14 -1.08 -1.02 -0.96 -0.90\n [37] -0.84 -0.78 -0.72 -0.66 -0.60 -0.54 -0.48 -0.42 -0.36 -0.30 -0.24 -0.18\n [49] -0.12 -0.06 0.00 0.06 0.12 0.18 0.24 0.30 0.36 0.42 0.48 0.54\n [61] 0.60 0.66 0.72 0.78 0.84 0.90 0.96 1.02 1.08 1.14 1.20 1.26\n [73] 1.32 1.38 1.44 1.50 1.56 1.62 1.68 1.74 1.80 1.86 1.92 1.98\n [85] 2.04 2.10 2.16 2.22 2.28 2.34 2.40 2.46 2.52 2.58 2.64 2.70\n [97] 2.76 2.82 2.88 2.94 3.00\n\n$y\n [1] 0.004431848 0.005296344 0.006306726 0.007482873 0.008846454 0.010420935\n [7] 0.012231526 0.014305109 0.016670101 0.019356277 0.022394530 0.025816575\n [13] 0.029654585 0.033940763 0.038706856 0.043983596 0.049800088 0.056183142\n [19] 0.063156561 0.070740393 0.078950158 0.087796071 0.097282269 0.107406075\n [25] 0.118157295 0.129517596 0.141459965 0.153948287 0.166937042 0.180371163\n [31] 0.194186055 0.208307790 0.222653499 0.237131952 0.251644341 0.266085250\n [37] 0.280343811 0.294305030 0.307851260 0.320863804 0.333224603 0.344818001\n [43] 0.355532529 0.365262673 0.373910605 0.381387815 0.387616615 0.392531483\n [49] 0.396080212 0.398224830 0.398942280 0.398224830 0.396080212 0.392531483\n [55] 0.387616615 0.381387815 0.373910605 0.365262673 0.355532529 0.344818001\n [61] 0.333224603 0.320863804 0.307851260 0.294305030 0.280343811 0.266085250\n [67] 0.251644341 0.237131952 0.222653499 0.208307790 0.194186055 0.180371163\n [73] 0.166937042 0.153948287 0.141459965 0.129517596 0.118157295 0.107406075\n [79] 0.097282269 0.087796071 0.078950158 0.070740393 0.063156561 0.056183142\n [85] 0.049800088 0.043983596 0.038706856 0.033940763 0.029654585 0.025816575\n [91] 0.022394530 0.019356277 0.016670101 0.014305109 0.012231526 0.010420935\n [97] 0.008846454 0.007482873 0.006306726 0.005296344 0.004431848\n\nqqPlot(X)\n\n\n\n\n\n\n\n\n[1] 12 26\n\ncheck_normality(X,sample.size=100, main = \"Y\")\n\nOK: raw appear as normally distributed (p = 0.407).\n\n\nThe rnonnorm() function in R generating a vector of random numbers sampled from a non-normal data with specified skewness and kurtosis using Fleishman’s Method.\n\n#Example of Non-Noemal distributed data\n\nlibrary(detectnorm)\nnonnorm <- numeric(0)\nfor(i in 1:500) {\nnonnorm<- rnonnorm(n = 100, mean = 0, sd = 1, skew = -1, kurt = 1)$dat}\nsummary(nonnorm)\n\n Min. 1st Qu. Median Mean 3rd Qu. Max. \n-3.40066 -0.37267 0.26446 0.02251 0.65110 1.31350 \n\nhist_n<-hist(nonnorm)\n\n\n\n\n\n\n\nhist_n\n\n$breaks\n [1] -3.5 -3.0 -2.5 -2.0 -1.5 -1.0 -0.5 0.0 0.5 1.0 1.5\n\n$counts\n [1] 1 2 2 4 5 9 15 24 27 11\n\n$density\n [1] 0.02 0.04 0.04 0.08 0.10 0.18 0.30 0.48 0.54 0.22\n\n$mids\n [1] -3.25 -2.75 -2.25 -1.75 -1.25 -0.75 -0.25 0.25 0.75 1.25\n\n$xname\n[1] \"nonnorm\"\n\n$equidist\n[1] TRUE\n\nattr(,\"class\")\n[1] \"histogram\"\n\nqqPlot(nonnorm)\n\n\n\n\n\n\n\n\n[1] 23 74\n\ncheck_normality(nonnorm, sample.size=100, main = \"Y\")\n\nWarning: Non-normality of raw detected (p < .001)."
},
{
"objectID": "Scripts/Script_5.html#more-than-two-variable",
"href": "Scripts/Script_5.html#more-than-two-variable",
"title": "Statistics",
"section": "More than two variable",
"text": "More than two variable\nWhen dealing with more than two predictor variables, there are several notations commonly used in this context:\nFor instance Y, X1 and X2 are variables:\n\nY∼X1: Indicates that Y is modeled by X1.\nY∼X1+X2: Indicates that Y is modeled using both X1 and X2, akin to multiple regression.\nY∼X1∗X2: Indicates that Y is modeled using X1, X2, and their interaction X1×X2.\nY∼(X1+X2)^2: Represents two-way interactions between X1 and X2. Note that typical mathematical powers apply here.\nY∼X1+I((X2^2): Indicates Y is modeled by X1 and X2^2, where the I function is used to encapsulate non-standard mathematical expressions.\nY∼X1∣X2: Denotes that Y is modeled by X1 conditioned on X2.\n\n#Principal Component Analysis Let’s take a look at the correlation matrix\n\nlibrary(corrr)\ncor_df <- df %>%\n dplyr::select(body_mass_g, ends_with(\"_mm\")) %>%\n correlate() %>%\n rearrange()\n\nCorrelation computed with\n• Method: 'pearson'\n• Missing treated using: 'pairwise.complete.obs'\n\ncor_df\n\n# A tibble: 4 × 5\n term flipper_length_mm body_mass_g bill_length_mm bill_depth_mm\n <chr> <dbl> <dbl> <dbl> <dbl>\n1 flipper_length_mm NA 0.873 0.653 -0.578\n2 body_mass_g 0.873 NA 0.589 -0.472\n3 bill_length_mm 0.653 0.589 NA -0.229\n4 bill_depth_mm -0.578 -0.472 -0.229 NA \n\n\nPreviously we used cor() to illustrate th correlation between features. There is a strong correlation observed between body mass and flipper length in the dataset. However, the bill variables do not show similarly strong correlations with other variables in the dataset.\n\nlibrary(dplyr)\ndf %>%\n dplyr::select(species, body_mass_g, ends_with(\"_mm\")) %>% \n GGally::ggpairs(aes(color = species),\n columns = c(\"flipper_length_mm\", \"body_mass_g\", \n \"bill_length_mm\", \"bill_depth_mm\")) +\n scale_colour_manual(values = c(\"darkorange\",\"purple\",\"cyan4\")) +\n scale_fill_manual(values = c(\"darkorange\",\"purple\",\"cyan4\"))\n\nRegistered S3 method overwritten by 'GGally':\n method from \n +.gg ggplot2\n\n\nWarning in geom_point(): All aesthetics have length 1, but the data has 16 rows.\nℹ Please consider using `annotate()` or provide this layer with data containing\n a single row.\n\n\n\n\n\n\n\n\n\nwe will applying some preprocessing steps which make the dataset ready for PCA:\n1- Eliminate any missing values (NA values).(done) 2- Center all predictors to have a mean of zero. 3- Scale all predictors to have unit variance.\n\nlibrary(recipes)\n\n\nAttaching package: 'recipes'\n\n\nThe following object is masked from 'package:stats':\n\n step\n\nrecipe_df <-\n recipe(~., data = df) %>% \n update_role(species, island, sex, year, new_role = \"id\") %>% \n step_naomit(all_predictors()) %>% \n step_normalize(all_predictors()) %>%\n step_pca(all_predictors(), id = \"pca\") %>% \n prep()\n\npca_df <- \n recipe_df %>% \n tidy(id = \"pca\") \n\npca_df\n\n# A tibble: 16 × 4\n terms value component id \n <chr> <dbl> <chr> <chr>\n 1 bill_length_mm 0.454 PC1 pca \n 2 bill_depth_mm -0.399 PC1 pca \n 3 flipper_length_mm 0.577 PC1 pca \n 4 body_mass_g 0.550 PC1 pca \n 5 bill_length_mm -0.600 PC2 pca \n 6 bill_depth_mm -0.796 PC2 pca \n 7 flipper_length_mm -0.00579 PC2 pca \n 8 body_mass_g -0.0765 PC2 pca \n 9 bill_length_mm -0.642 PC3 pca \n10 bill_depth_mm 0.426 PC3 pca \n11 flipper_length_mm 0.236 PC3 pca \n12 body_mass_g 0.592 PC3 pca \n13 bill_length_mm 0.145 PC4 pca \n14 bill_depth_mm -0.160 PC4 pca \n15 flipper_length_mm -0.782 PC4 pca \n16 body_mass_g 0.585 PC4 pca \n\n\nFor each component, the value indicates the linear combination of weights assigned to each variable contributing to that component.\n\nprcomp_df <- df %>% \n dplyr::select(body_mass_g, ends_with(\"_mm\")) %>% \n tidyr::drop_na() %>% \n scale() %>% \n prcomp() %>% #Performs a principal components analysis on the given data matrix and returns the results as an object of class prcomp.\n .$rotation\nprcomp_df\n\n PC1 PC2 PC3 PC4\nbody_mass_g 0.5496747 0.07646366 -0.5917374 -0.5846861\nbill_length_mm 0.4537532 0.60019490 0.6424951 -0.1451695\nbill_depth_mm -0.3990472 0.79616951 -0.4258004 0.1599044\nflipper_length_mm 0.5768250 0.00578817 -0.2360952 0.7819837\n\n\nA tidy representation achieved using the above code.\n\n#To examine how much variance each component accounts for:\nrecipe_df %>% \n tidy(id = \"pca\", type = \"variance\") %>% \n dplyr::filter(terms == \"percent variance\") %>% \n ggplot(aes(x = component, y = value)) + \n geom_col(fill = \"#b6dfe2\") + \n xlim(c(0, 5)) + \n ylab(\"% of total variance\")\n\n\n\n\n\n\n\n\nTo plot the loadings by principal component, we can use a bar plot visualization method.\n\npca_df %>%\n mutate(terms = tidytext::reorder_within(terms, \n abs(value), \n component)) %>%\n ggplot(aes(abs(value), terms, fill = value > 0)) +\n geom_col() +\n facet_wrap(~component, scales = \"free_y\") +\n tidytext::scale_y_reordered() +\n scale_fill_manual(values = c(\"#b6dfe2\", \"#0A537D\")) +\n labs(\n x = \"Absolute value of contribution\",\n y = NULL, fill = \"Positive?\"\n ) \n\n\n\n\n\n\n\n\nTo plot the data in a wide format, you can reshape it accordingly.\n\npca_wider <- pca_df %>% \n tidyr::pivot_wider(names_from = component, id_cols = terms)\n\nTo extract the PCA scores from PCA calculated data use the recipes::juice() function:\n\n# define arrow style\narrow_style <- arrow(length = unit(.05, \"inches\"),\n type = \"closed\")\n\n\npca_plot <-\n juice(recipe_df) %>%\n ggplot(aes(PC1, PC2)) +\n geom_point(aes(color = species, shape = species), \n alpha = 0.8, \n size = 2) +\n scale_colour_manual(values = c(\"darkorange\",\"purple\",\"cyan4\")) \n\npca_plot +\n geom_segment(data = pca_wider,\n aes(xend = PC1, yend = PC2), \n x = 0, \n y = 0, \n arrow = arrow_style) + \n geom_text(data = pca_wider,\n aes(x = PC1, y = PC2, label = terms), \n hjust = 0, \n vjust = 1,\n size = 5, \n color = '#0A537D')\n\n\n\n\n\n\n\n\nInitially, directing your attention to the x-axis depicting the first principal component, it becomes evident that flipper length and body mass play significant roles (reaffirming observations from the preceding bar chart). Along this dimension, Gentoo penguins distinctly stand out from the other two species.\n\ndf %>% \n group_by(species) %>% \n summarize(across(c(flipper_length_mm, body_mass_g), \n mean, \n na.rm = TRUE)) \n\n# A tibble: 3 × 3\n species flipper_length_mm body_mass_g\n <fct> <dbl> <dbl>\n1 Adelie 190. 3706.\n2 Chinstrap 196. 3733.\n3 Gentoo 217. 5092.\n\n\n\nggplot(df, aes(x = flipper_length_mm, y = body_mass_g, colour = species)) +\n geom_point() +\n scale_colour_manual(values = c(\"darkorange\",\"purple\",\"cyan4\")) \n\n\n\n\n\n\n\n\n\npca_plot %+% \n aes(PC2, PC3) +\n geom_segment(data = pca_wider,\n aes(xend = PC2, yend = PC3), \n x = 0, \n y = 0, \n arrow = arrow_style) + \n geom_text(data = pca_wider,\n aes(x = PC2, y = PC3, label = terms), \n hjust = 0, \n vjust = 1,\n size = 5, \n color = '#0A537D') \n\n\n\n\n\n\n\n\n\ndf %>% \n group_by(species) %>% \n summarize(across(c(bill_depth_mm, bill_length_mm), \n mean, \n na.rm = TRUE))\n\n# A tibble: 3 × 3\n species bill_depth_mm bill_length_mm\n <fct> <dbl> <dbl>\n1 Adelie 18.3 38.8\n2 Chinstrap 18.4 48.8\n3 Gentoo 15.0 47.6\n\n\n\nggplot(df, aes(x = bill_length_mm, y = bill_depth_mm, colour = species)) +\n geom_point() +\n scale_colour_manual(values = c(\"darkorange\",\"purple\",\"cyan4\")) \n\n\n\n\n\n\n\n\n\nlibrary(ggbiplot)\n\nLoading required package: plyr\n\n\n------------------------------------------------------------------------------\n\n\nYou have loaded plyr after dplyr - this is likely to cause problems.\nIf you need functions from both plyr and dplyr, please load plyr first, then dplyr:\nlibrary(plyr); library(dplyr)\n\n\n------------------------------------------------------------------------------\n\n\n\nAttaching package: 'plyr'\n\n\nThe following object is masked from 'package:FSA':\n\n mapvalues\n\n\nThe following objects are masked from 'package:dplyr':\n\n arrange, count, desc, failwith, id, mutate, rename, summarise,\n summarize\n\n\nLoading required package: scales\n\n\nWarning: package 'scales' was built under R version 4.3.2\n\n\nLoading required package: grid\n\ndf.pca <- prcomp (~ bill_length_mm + bill_depth_mm + flipper_length_mm + body_mass_g,\n data=df,\n na.action=na.omit, # not actually necessary: we removed NA\n scale. = TRUE)\n\ndf.pca\n\nStandard deviations (1, .., p=4):\n[1] 1.6569115 0.8821095 0.6071594 0.3284579\n\nRotation (n x k) = (4 x 4):\n PC1 PC2 PC3 PC4\nbill_length_mm 0.4537532 -0.60019490 -0.6424951 0.1451695\nbill_depth_mm -0.3990472 -0.79616951 0.4258004 -0.1599044\nflipper_length_mm 0.5768250 -0.00578817 0.2360952 -0.7819837\nbody_mass_g 0.5496747 -0.07646366 0.5917374 0.5846861\n\nggbiplot(df.pca, obs.scale = 1, var.scale = 1,\n groups = df$species, \n ellipse = TRUE, circle = TRUE) +\n scale_color_discrete(name = 'Penguin Species') +\n theme_minimal() +\n theme(legend.direction = 'horizontal', legend.position = 'top')"
}
]