
















Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
This page cannot be seen from the preview
Don't miss anything!

















R is a programming language and software environment that has become the first choice for statistical computing and data analysis. Developed in the early 1990s by Ross Ihaka and Robert Gentleman, R was built to simplify complex data manipulation and create clear, customizable visualizations. Over time, it has gained popularity among statisticians, data scientists and researchers because of its capabilities and the vast array of packages available. R is preferred: Free and Open-Source: R is open to everyone, meaning users can modify, share and distribute their work freely. Designed for Data: R is built for data analysis, offering a comprehensive set of tools for statistical computing and graphics. Large Package Repository: The Comprehensive R Archive Network (CRAN) offers thousands of add-on packages for specialized tasks. Cross-Platform Compatibility: R can work on Windows, Mac and Linux operating systems. Great for Visualization: With packages like ggplot2 , R makes it easy to create informative, interactive
R's key features:
2. Data Handling and Visualization: Data Import and Export: R can handle data from various sources, including databases, spreadsheets, and text files. Data Manipulation: R offers powerful tools for data cleaning, transformation, and reshaping using packages like dplyr, tidyr, and data.table. Data Visualization: R excels in creating high-quality static, animated, and interactive visualizations with libraries like ggplot2, lattice, and plotly
Interactive Interface: R provides an interactive environment for exploring data and testing code. Integration with Other Languages: R can be integrated with other programming languages like C, C++, and Java. Reproducible Research: R Markdown allows users to combine code, output, and narrative in a single document for reproducible analysis. Applications of R R is used in a variety of fields, including: Data Science and Machine Learning : R is widely used for data analysis, statistical modeling and machine learning tasks. Finance: Financial analysts use R for quantitative modeling and risk analysis. Healthcare: In clinical research, R helps analyze medical data and test hypotheses. Academia: Researchers and statisticians use R for data analysis and publishing reproducible research. Advantages of R Programming Comprehensive Statistical Tools: R includes many statistical functions and models, making it the ideal choice for data analysis. Customizable Visualizations: R’s visualization tools allows for customizations for a simple bar chart or a detailed heatmap. Extensive Community Support : R has a large user base and there are countless resources, forums and tutorials available. Highly Extendable: The availability of over 15,000 R packages means we can extend R's functionality to suit any project or need. Disadvantages of R Programming Memory Intensive: R can be slow with very large datasets, consuming a lot of memory. Limited Support for Error Handling: Unlike some other programming languages, R has less robust error handling features. Steeper Learning Curve: Beginners might face challenges with some of R’s complex features and syntax. Performance: R’s performance can lag behind languages like Python or C++ when it comes to speed, especially for large-scale operations.
It can refer to two main concepts: The R Programming Environment (Software): This refers to the entire system that allows users to perform statistical computing and data analysis using the R language. It includes: The R language interpreter: The core component that executes R code. The R console (or GUI): The interactive interface where users can type and run R commands. Packages : Collections of functions, data, and compiled code that extend R's capabilities, covering a wide range of statistical methods and data manipulation tools. Development tools : Such as RStudio, which is an Integrated Development Environment (IDE) that provides a more user-friendly interface for writing, debugging, and managing R projects. Environments within R (Programming Concept): This refers to a fundamental concept in the R programming language related to how objects (variables, functions, etc.) are stored and accessed. An environment is essentially a collection of name-value pairs, where names are bound to specific objects. The Global Environment (R_GlobalEnv) is the top-level environment where objects created at the R command prompt reside. Function environments : are created when functions are called, allowing for local variables and a defined scope for object access.
The capacity to organise and share your work with your partners more effectively through the creation of projects. Plot snippets Simple terminal and console switching Tracking of operational history There are numerous articles from RStudio Support on using the IDE. Set the working directory in R Studio R is always pointed at a directory on our computer. We can find out which directory by running the getwd() function. Note: this function has no arguments. We can set the working directory manually in two ways: The first way is to use the console and using the command setwd("directorypath"). You can use this function setwd() and give the path of the directory which you want to be the working directory for R studio, in the double codes. The second way is to set the working directory from the GUI. To set the working directory from the GUI you have to click on this 3 dots button. When you click this, this will open up a file browser, which will help you to choose your working directory. R Studio Once you choose your working directory, you need to use this setting button in the more tab and click it and then you get a popup menu, where you need to select "Set as working directory". This will select the current directory, which you have chosen using this file browser as your working directory. Once you set the working directory, you are ready to program in R Studio. Create an RStudio project Step 1: Select the FILE option and select create option.
Step 2: Then select the New Project option.
Finally, project are created in a specific location Navigating directories in R studio getwd() : Returns the current working directory. setwd() : Set the working directory. dir(): Return the list of the directory. sessionInfo() : Return the session of the windows. date() : Return the current date.
uniqv[which.max(tabulate(match(v, uniqv)))] } x <- c(1, 2, 2, 3, 3, 3, 4) print(get_mode(x)) # Output: [1] 3 Storage Mode (or "type") of an Object: This refers to the fundamental data type or storage representation of an R object, such as a vector, matrix, or data frame. The mode() function in R returns this storage mode. Common modes include: o numeric: For numbers (integers and doubles). o character: For text strings. o logical: For TRUE or FALSE values. o complex: For complex numbers. o raw: For raw byte data. o list: For lists. o function: For functions. Code v_numeric <- c(1, 2, 3) print(mode(v_numeric)) # Output: [1] "numeric" v_char <- c("apple", "banana") print(mode(v_char)) # Output: [1] "character" It is crucial to distinguish between these two meanings of "mode" when working with R. The context of the usage will determine which interpretation is relevant.
Operators are used to perform operations on variables and values. In the example below, we use the + operator to add together two values: Example 10 + 5 R divides the operators in the following groups: Arithmetic operators Assignment operators Comparison operators Logical operators Miscellaneous operators R Arithmetic Operators Arithmetic operators are used with numeric values to perform common mathematical operations: Operator Name Example
= (Can also be used for assignment, but <- is preferred for clarity) - > (Assigns a value to a variable on the right) Example my_var <- 3 or 3 - > my_var my_var # print my_var Note: x <- 3 is equal to 3 - > x R Comparison Operators Comparison operators are used to compare two values: Operator Name Example == Equal x == y != Not equal x != y > Greater than x > y < Less than x < y >= Greater than or equal to x >= y <= Less than or equal to x <= y R Logical Operators Logical operators are used to combine conditional statements: Operator Description & Element-wise Logical AND operator. Returns TRUE if both elements are TRUE && Logical AND operator - Returns TRUE if both statements are TRUE | Elementwise- Logical OR operator. Returns TRUE if one of the statements is TRUE || Logical OR operator. Returns TRUE if one of the statements is TRUE ! Logical NOT - Returns FALSE if statement is TRUE
The different parts of a function are − Function Name − This is the actual name of the function. It is stored in R environment as an object with this name. Arguments − An argument is a placeholder. When a function is invoked, you pass a value to the argument. Arguments are optional; that is, a function may contain no arguments. Also arguments can have default values. Function Body − The function body contains a collection of statements that defines what the function does. Return Value − The return value of a function is the last expression in the function body to be evaluated. R has many in-built functions which can be directly called in the program without defining them first. We can also create and use our own functions referred as user defined functions. Built-in Function Simple examples of in-built functions are seq() , mean() , max() , sum(x) and paste(...) etc. They are directly called by user written programs. Category Function Mathematical Functions abs(), sqrt(), round(), exp(), log(), cos(), sin(), tan() Statistical Functions mean(), median(), cor(), var() Data Manipulation Functions unique(), subset(), aggregate(), order() File Input/Output Functions read.csv(), write.csv(), read.table(), write.table() **# Create a sequence of numbers from 32 to 44. print(seq( 32 , 44 ))
print(mean( 25 : 82 ))
print(sum( 41 : 68 ))** it produces the following result − [1] 32 33 34 35 36 37 38 39 40 41 42 43 44 [1] 53. [1] 1526
We can create user-defined functions in R. They are specific to what a user wants and once created they can be used like the built-in functions. Below is an example of how a function is created and used. Single Input Single Output Now create a function in R that will take a single input and gives us a single output. Example-1:
areaOfCircle = function(radius){ area = pi*radius^ print(area) } areaOfCircle(2)
Multiple Input Multiple Output Now create a function in R Language that will take multiple inputs and gives us multiple outputs using a list. Rectangle = function(length= 5 , width= 4 ){ area = length * width return(area) } # Case 1: print(Rectangle( 2 , 3 )) # Case 2: print(Rectangle(width = 8 , length = 4 )) # Case 3: print(Rectangle())
Help () in R R provides several ways to access help and documentation for functions, packages, and other objects.
statements .... .... } else{ statements .... .... } Example: x <- 5 # Check value is less than or greater than 10 if (x > 10 ){ print(paste(x, "is greater than 10")) } else { print(paste(x, "is less than 10")) } Output: [1] "5 is less than 10" for loop It is a type of loop or sequence of statements executed repeatedly until exit condition is reached. Syntax: for(value in vector){ statements .... .... } Example: x <- letters[ 4 : 10 ] for (i in x){ print(i) } Output: [1] "d" [1] "e" [1] "f" [1] "g" [1] "h" [1] "i"
[1] "j" Nested loops Nested loops are similar to simple loops. Nested means loops inside loop. Moreover, nested loops are used to manipulate the matrix. Example: # Defining matrix m <- matrix( 2 : 15 , 2 ) for (r in seq(nrow(m))) { for (c in seq(ncol(m))) { print(m[r, c]) } } Output: [1] 2 [1] 4 [1] 6 [1] 8 [1] 10 [1] 12 [1] 14 [1] 3 [1] 5 [1] 7 [1] 9 [1] 11 [1] 13 [1] 15 while loop while loop is another kind of loop iterated until a condition is satisfied. The testing expression is checked first before executing the body of loop.(flow chart) Syntax: while(expression){ statement .... .... } Example: x = 1
return statement is used to return the result of an executed function and returns control to the calling function. Syntax: return(expression) Example: # Checks value is either positive, negative or zero func <- function(x){ if (x > 0 ){ return ("Positive") } else if (x < 0 ){ return ("Negative") } else { return ("Zero") } } func( 1 ) func( 0 ) func(- 1 ) Output: [1] "Positive" [1] "Zero" [1] "Negative" next statement next statement is used to skip the current iteration without executing the further statements and continues the next iteration cycle without terminating the loop. Example: # Defining vector x <- 1 : 10 # Print even numbers for (i in x){ if (i%%2 != 0 ){ next #Jumps to next loop } print(i) } Output: [1] 2 [1] 4 [1] 6 [1] 8 [1] 10
R Vectors are the same as the arrays in R language which are used to hold multiple data values of the same type. One major key point is that in R Programming Language the indexing of the vector will start from '1' and not from '0'. We can create numeric vectors and character vectors as well.
1. Creating a vector in R A vector is a basic data structure that represents a one-dimensional array. to create a array we use the "c" function which the most common method use in R Programming Language. We can also use seq() function or use colons ":" also as shown in the example. X<- c( 61 , 4 , 21 , 67 , 89 , 2 ) cat('using c function', X, '\n') Y<- seq( 1 , 10 , length.out = 5 ) cat('using seq() function', Y, '\n') Z<- 2 : cat('using colon', Z) Output: using c function 61 4 21 67 89 2 using seq() function 1 3.25 5.5 7.75 10 using colon 2 3 4 5 6 7 2. Types of R vectors Vectors are of different types which are used in R. Following are some of the types of vectors: 2.1 Numeric vectors Numeric vectors are those which contain numeric values such as integer, float, etc. The L suffix in R is used to specify that a number is an integer and not a numeric (floating-point) value. v1 <- c( 4 , 5 , 6 , 7 ) typeof(v1) v2 <- c(1L, 4L, 2L, 5L) typeof(v2) Output: [1] "double" [1] "integer" 2.2 Character vectors Character vectors in R contain alphanumeric values and special characters. In R, when a vector contains elements of mixed types (like characters and numbers), R automatically coerces the entire vector to a single type. Since characters are more general than numbers in R, the vector is coerced to a character vector. v1 <- c('geeks', '2', 'hello', 57 ) typeof(v1) Output: [1] "character" 2.3 Logical vectors Logical vectors in R contain Boolean values such as TRUE, FALSE and NA for Null values. In R, NA is a special value used to represent missing or undefined data. When used in a logical vector, NA is treated as a logical value because it is specifically designed to work with logical vectors and other types of data. v1 <- c( TRUE , FALSE , TRUE , NA ) typeof(v1) Output: [1] "logical"
6. Deleting a R vector Deletion of a Vector is the process of deleting all of the elements of the vector. This can be done by assigning it to a NULL value. M <- c( 8 , 10 , 2 , 5 ) M <- NULL print(cat('Output vector', M, "\f")) Output: Output vector NULL 7. Sorting elements of a R Vector sort() function is used with the help of which we can sort the values in ascending or descending order. X <- c( 8 , 2 , 7 , 1 , 11 , 2 ) A <- sort(X) cat('ascending order', A, '\n') B <- sort(X, decreasing = TRUE ) cat('descending order', B) Output: ascending order 1 2 2 7 8 11 descending order 11 8 7 2 2 1 Generating Sequenced Vectors One of the examples on top, showed you how to create a vector with numerical values in a sequence with the : operator: Example numbers <- 1 : 10 numbers operations on vectors in R programming: creating deleating accessing modifying generating sorting
We can see vector recycling, when we perform some kind of operations like addition, subtraction... .etc on two vectors of unequal length. The vector with a small length will be repeated as long as the operation completes on the longer vector. How it works: Unequal Lengths: When you apply a binary operator (like +, - , *, /, or comparison operators) to two vectors with different numbers of elements, R identifies the shorter vector. Repetition: The elements of the shorter vector are repeated from the beginning, in their original order, until the recycled vector has the same length as the longer vector. Operation:
The element-wise operation is then performed between the elements of the longer vector and the newly recycled (and now equally long) shorter vector. Important Considerations: Warning Message: If the length of the longer vector is not an exact multiple of the length of the shorter vector, R will still perform the recycling and the operation, but it will issue a warning message indicating that "longer object length is not a multiple of shorter object length." This warns you that the recycling resulted in a truncated repetition of the shorter vector. Common Use Cases: Vector recycling is frequently encountered in various scenarios, including: Arithmetic operations: c(1, 2, 3) + c(10, 20) Logical comparisons: c(TRUE, FALSE, TRUE, FALSE) & c(TRUE, FALSE) Indexing with logical vectors. Example: Code vec1 <- 1: vec2 <- 1:
result <- vec1 + vec print(result) Output: Code [1] 2 4 4 6 6 8 Recycling In R "recycling" refers to the automatic repetition of elements from a shorter vector when performing vectorized operations with a longer vector. This mechanism allows R to perform element-wise operations on vectors of unequal lengths. How Recycling Works: When an operation (like addition, subtraction, multiplication, division, or comparison) is applied to two vectors of different lengths, R will repeat the elements of the shorter vector from its beginning until its length matches the length of the longer vector. The operation is then performed element by element. Example: Code
vec1 <- c(1, 2, 3) vec2 <- c(10, 20, 30, 40, 50)
result <- vec1 + vec print(result) Output: Code [1] 11 22 33 41 52 Warning message: In vec1 + vec2 : longer object length is not a multiple of shorter object length