UNIT-1

  

Introduction to R

R Programming language is used for performing statistical computing as well as graphical processing of data. It was developed by Ross Ihaka and Robert Gentleman at University of Auckland, New Zealand.

Various data scientists, statisticians and data analysts use the R programming language for analyzing data and carrying out statistical analysis using visualizations. With the help of R, you can perform data analysis on structured and unstructured data.

R first appeared in 1993 as an implementation of the S programming language. The term R comes from the fact that both of its creators’ names begin with the initial of R. Version 3.5.1 rolled out in July of 2018; we call it Feather Spray. This is a programming language and a free software environment for statistical computing and graphics. One can often find statisticians and data miners using it to develop statistical software and for data analysis.

Basics of R:

  1. Syntax and Functions: R syntax is relatively simple, making it beginner-friendly. Functions are the building blocks of R and can be used to perform operations on data. Examples of common functions include mean(), sum() and plot().
  2. Data Types and Objects: R has several built-in data types like numeric, integer, character and logical, as well as complex data structures such as vectors, matrices, lists, and data frames.
  3. Packages and Libraries: The install.packages() and library() functions make it easy to download and other sources like Bio-conductor.
  4. Data Import and Export: R can import data from various sources, including CSV, EXCEL, databases and web APIs, making it versatile for data extraction and integration. The read.csv() and write.csv() functions, for example, are commonly used for CSV data handling.
  5. Reproducible Research and Reporting: With tools like RMarkdown and knitr, R can generate reports, presentations and documents that combine code, analysis and narrative. This feature promotes reproducible research, as analyses and results can be rerun and verified with ease.

Advantages of Using R

  • Specialized for Statistics and Data Analysis: R was designed by statisticians for statisticians, so it is inherently powerful for analysis and has tools specifically tailored to this purpose.
  • Cost-Effective: As an open-source language, R is free to use and offers cost-effective solutions to complex data problems.
  • Extensive Visualization Tools: R’s visualization libraries are among the most advanced, making it a great choice for generating insights visually.

Strengths of R

  • Specialized for Data Analysis: R is designed for statistical computing and data visualization, making it ideal for data-driven fields.
  • Open-Source and Free: R is freely available, providing an accessible and cost-effective solution for data analysis.
  • Strong Community Support: R has a large, active community that provides a wealth of resources, from documentation to open-source packages.

Limitations of R

  • Memory Management: R is memory-bound, so it can struggle with very large datasets.
  • Steep Learning Curve for Advanced Techniques: Although R is beginner-friendly, mastering advanced statistical and machine learning techniques can be challenging.

Applications of R:

  • Data Science and Machine Learning: R is used extensively in data science and machine learning projects. It has a wide range of libraries and packages that make it easy to clean, manipulate, and analyze data. R also has built-in visualization tools that make it easy to create interactive data visualizations.
  • Predictive modeling: R is widely used in Predictive modeling, it has a lot of powerful packages for statistical modeling, and it is commonly used in industries such as finance and insurance to forecast future trends and make decisions based on that.
  • Healthcare: R is being used in the healthcare industry for data analysis and visualization. It’s used for creating models to predict patient outcomes, analyzing electronic health records, and identifying patterns in large datasets to improve patient care.
  • Business: R is used by many businesses for data analysis and visualization. It can be used to analyze customer data, predict sales trends, and create data-driven marketing campaigns.
  • Social Media Analysis: R is used to analyze and visualize data from social media platforms like Twitter, Facebook, and Instagram. This allows businesses to track sentiment and engagement, identify influencers, and gain insights into their target audience.
  • Research: R is widely used in research, it is a powerful tool for statisticians, researchers and scientists to analyze and visualize data. It has a wide range of libraries and packages that are specifically designed for research applications, such as genetics, ecology, and sociology.

R programming is a powerful tool that is used in tons of industries. It is widely adopted in data science, machine learning, predictive modeling, healthcare, business, social media analysis, and research. It’s a valuable skill for anyone who wants to become a data scientist.

R-Data Types

For correct processing, a programming language must know what can and cannot be done to a particular value. For example, addition cannot be performed on the words ‘hello’ and ‘world’, one cannot change the numbers 1 and -34.5 from lower to uppercase. Due to this, R has a feature called the data types. 

Different kinds of values are assigned different data types that help differentiate them. These types have certain characteristics and rules associated with them that define their properties.

Choosing the appropriate data type for variables and data structures is essential for efficient memory usage and code performance. In R, selecting the most suitable data type based on the nature of the data and the operations to be performed can lead to more readable and maintainable code.

R provides the class() and typeof() functions to find out what is the class and type of any variable. R has five data types which are:

  1. Numeric
  2. Integers
  3. Complex
  4. Logical
  5. Characters

1. Numeric Data Type

The numeric data type is for numeric values. It is the default data type for numbers in R. Examples of numeric values would be 1, 34.5, 3.145, -24, -45.003, etc.

Note: When R stores a number in a variable, it converts the number into a ‘double’ value or a decimal type with at least two decimal places. This means that a value such as ’1’ is stored as 1.00 with a type of double and a class of numeric.

2. Integers Data Type

The Integer data type is used for integer values. To store a value as an integer, one need to specify it as such. The integer data type is commonly used for discrete only values like unique ids. One can store as well as convert a value into an integer type using the as.integer() function.



One can also use the capital ‘L’ notation to denote that a particular value is of the integer data type.


3. Complex Data Type

The complex data type is to store numbers with an imaginary component. Examples of complex values would be 1+2i, 3i, 4-5i, -12+6i, etc.


4. Logical Data Type

The logical data type stores logical or boolean values of TRUE or FALSE.



5. Character Data Type

The character data type stores character values or strings. Strings in R can contain the alphabet, numbers, and symbols. The easiest way to denote that a value is of character type in R is to wrap the value inside single or double inverted commas.


One can also use the as.character() function to store a value as a character or to convert a value to the character data type.

Activity: Conversion of Data Types in R

Hint: 

1. Conversion into Numeric

We can use the as.numerical function to convert the values of other data types into numerical values. The conversion follows a few rules, which are:

  • To convert an integer value into a numeric, we can use the as.numeric function.
  • To convert a complex value into numeric by using the function. This removes the imaginary part of the number.
  • Logical values can be converted into numeric as well by the function. The TRUE value is converted to 1, and FALSE is converted to 0.
  • Character values can similarly be converted into numerical values but if the string contains letters, alphabets and symbols then the numeric value becomes NA.

2. Conversion into Integer


The as.integer function can convert the values of other data types into integer values according to the following rules:

  • Numeric values can be converted into an integer using the function. This removes any decimal values from the number.
  • Complex values can also be converted into integers. The function removes the imaginary parts of the number.
  • The conversion from logical values to integers is similar to the conversion of logical values to numerics. TRUE is converted to 1, and FALSE is converted to 0.
  • Character values can be converted into integers as well by using the as.integer function. This conversion follows the same rules as the character to numeric conversion.
3. Conversion into Complex

Using the as.complex function, we can convert other values into the complex data types. The conversion takes place according to the following rules:

  • Numeric values can be converted into complex by using the as.complex function or by adding an imaginary part to it.
  • Integer value can also be converted into complex values similarly.
  • Logical values become 0+0i for FALSE and 1+0i for TRUE when converted into complex values using the as.complex function. We can also convert a logical value into a complex value by adding an imaginary part to it.
  • The conversion from a character to a complex is the same as the conversion from character to numeric or an integer with 0i added to the converted value if it is not NA.

4. Conversion into Logical

Conversion into logical data type can be done by using the as.logical function, by following the given rules:

  • Numeric, integer, and complex values can be converted into logical values, but the function returns FALSE if the value is zero and TRUE if it is anything else.
  • Character values when converted by the as.logical function, always return NA.
5. Conversion into character

One can convert a value of any data type into character data type using the as.character function. The function converts the original value into a character string.


Basic Objects and Data Structures:

In any programming language, if you are doing programming, one need to use different variables to store different data. Moreover, variables are reserved in a memory location to store values. Also, this implies that, once you create a variable you reserve some area in memory. Further, data structures are the only way of arranging data so it can be used efficiently on a computer.

If we see in contrast to different programming languages like C and Java, R doesn’t have variables declared as some data type. Further, the variables are appointed with R-objects and the knowledge form of the R-object becomes the datatype of the variable. There are many types of R-objects. The popularly used ones are:

  • Vector
  • Matrix
  • Array
  • Lists
  • Data Frames

1. Vector

Vector is the most basic data structure in R programming language. It comes in two parts: Atomic vectors and Lists. They have three common properties:

  • Type function – what actually it is?
  • Length function – how many elements does it contain.
  • Attribute function – extra arbitrary metadata.

These elements have different types. For instance, atomic vectors must share the same type. On the contrary, elements that are present in a list can have different data types. 

Atomic Vectors

There are four common types of R Atomic Vectors:

  • Numeric Data Type
  • Integer Data Type
  • Character Data Type
  • Logical Data Type

[In other words, it is a one-dimensional array that holds elements of a single data type which can be created using c(), e.g., c(1, 2, 3)]. 

Numeric Vector: c(1.5, 2.3, 3.7)

Character Vector: c("apple", "banana")

Logical Vector: c(TRUE, FALSE)

2. Matrix

 A matrix is a two-dimensional rectangular data set and thus it can be created using vector input to the matrix function. In addition, a matrix is a collection of numbers arranged into a fixed number of rows and columns. Usually, the numbers are the real numbers. By using a matrix function, one can reproduce a memory representation of the matrix in R. Hence, the data elements must be of the same basic type.

#One can also access the element present at the mth row and nth column as follows:

<-mat1[1,2] Ans: 3
<-mat2[2,1] Ans: 5

# also extract the entire mth row and nth row separately as follows:
<-mat1[2, ] Ans: 2 4
<-mat2[ , 2] Ans: 6 7 as a column

# Adding, subtraction, multiplication and division of two matrices 
<- mat1+mat2  
<- mat1-mat2
<-4*mat1
<-mat1/mat2

# Transpose
<-t(mat1)
# Identity matrix
<-diag(4)

3. Array

In R Programming, arrays are multi-dimensional Data structures. In an array, data is stored in the form of matrices, row and as well as in columns. 

Arrays in R are the data objects which can store data in more than two dimensions. An array is created using the array() function. One can use vectors as input to create an array.  

For example:

In this following example, we will create an array in R of two 3×3 matrices each with 3 rows and 3 columns.


# One can give names to the rows, columns, and matrices in the array by using the dimnames parameter.
vec1<-c(1,2,4)
vec2<-c(15,17,27,3,10,11)
col_name<-c("col1","col2","col3")
row_name<-c("row1","row2","row3")
matrix_name<-c("matrix1","matrix2")
output<-array(c(vec1,vec2,dim=c(3,3,2), dimnames=list(rownames, colnames,matrix_name))
vec1 <- c(1,2,4)
vec2 <- c(15,17,27,3,10,11)
column_names <- c(“col1″,”col2″,”col3”)
row_names <- c(“row1″,”row2″,”row3”)
matrix_names <- c(“Mat1″,”Mat2”)

4. List 

Lists are the objects which contain elements of different types – like strings, numbers, vectors and another list inside them. A list can also contain a matrix or a function as its elements. In other words, a list is a generic vector containing other objects. A list is created using the list() function.

5. Data Frame 

 The concept comes from the world of the statistical software used in empirical research. It generally refers to tabular data: a data structure representing the cases (rows), each of which consists of numbers of observation or measurement (columns).

A data frame is used for storing data tables. It is a list of vectors of equal length.


A data frame is an array. Unlike an array, the data we store in the columns of the data frame can be of various types. That is, one column might be a numeric variable, another might be a factor, and a third might be a character variable. All columns have to be of the same length.

Characteristics of a Data Frame:

  • The column names should be non-empty.
  • The row names should be unique.
  • The data stored in a data frame can be of numeric, factor or character type.
  • Each column should contain the same number of data items.
6. NULL: 
 Represents the absence of a value or empty object in R.
 
7. Special Values: R has specific representations for:
          NA: Missing values
          NaN: Not a Number, e.g., for undefined math operations like 0/0
          Inf and -Inf: Positive and negative infinity values.

8. Factor: Used to represent categorical data with a fixed number of unique values or levels. Defined with factor() and stores both the values and their underlying integer codes.
Source: data-flair.training

Rounding in R

Rounding in R involves adjusting a numerical value to a specified number of decimal places or to the nearest integer. R provides several functions for different rounding behaviors.

1. This is the most common rounding function. It rounds to the nearest number, with .5 typically rounding up in R.

    round(x, digits = 0) 

  • x: The numeric vector to be rounded.

  • digits: The number of decimal places to round to. If digits = 0 (default), it rounds to the nearest integer.

2. floor(x): Returns the largest integer less than or equal to x. It always rounds down towards negative infinity.

3. ceiling(x): Returns the smallest integer greater than or equal to x. It always rounds up towards positive infinity. 

4. trunc(x): Truncates the number towards zero. For positive numbers, it's like floor(); for negative numbers, it's like ceiling(). It simply removes the decimal part. 

5. signif(x, digits = 6): Rounds to a specified number of significant digits, not decimal places.

# Example data

num <- 3.14159

neg_num <- -2.718

# 1. round()

round(num)         # Rounds to nearest integer (3)

round(num, 2)      # Rounds to 2 decimal places (3.14)

round(3.5)         # Rounds up (4)

round(2.5)         # Rounds up (3)

round(-3.5)        # Rounds up (to -3, as it rounds away from zero for .5)

# 2. floor()

floor(num)         # 3

floor(neg_num)     # -3 (largest integer less than or equal to -2.718 is -3)

# 3. ceiling()

ceiling(num)       # 4

ceiling(neg_num)   # -2 (smallest integer greater than or equal to -2.718 is -2)

# 4. trunc()

trunc(num)         # 3

trunc(neg_num)     # -2 (truncates towards zero)

# 5. signif()

signif(num, 3)     # 3.14 (3 significant digits)

signif(12345, 2)   # 12000 (2 significant digits)

Variable Names in R

In R, variables are used to store data. You give a name to a piece of data and then one can refer to that data using its name.

Rules for Variable Names:

  • It can contain letters (a-z, A-Z), digits (0-9), underscores (_), and periods (.).

  • It must start with a letter or a period not followed by a number. (e.g., .var is valid, .2var is not).

  • Case-sensitive (myVar is different from myvar).

  • Cannot be reserved keywords (e.g., if, else, for, function, TRUE, FALSE).

  • Conventionally, names are often in snake_case (e.g., my_variable) or camelCase (e.g., myVariable).

# Variable names are case-sensitive
MyVariable <- 5
print(my_variable) # Still 10
print(MyVariable)  # 5

# Invalid variable names (examples)
# 2nd_variable <- "Error" # Cannot start with a digit
# if <- "keyword" # Cannot be a reserved keyword


Operators in R

1). Arithmetic operators

R performs standard arithmetic operations in an intuitive way. It can handle scalar values, vectors and matrices. When performing operations on vectors, R uses element-wise application, which is a powerful feature for vectorized computations.

Common Arithmetic Operators:

  • Addition (+)

  • Subtraction (-)

  • Multiplication (*)

  • Division (/)

  • Exponentiation (power) (^ or **)

Examples: 

# Scalar operations

a <- 10

b <- 3

a + b  # 13

a - b  # 7

a * b  # 30

a / b  # 3.333333

a ^ 2  # 100

a ** 3 # 1000

# Vector operations (element-wise)

vec1 <- c(1, 2, 3)

vec2 <- c(4, 5, 6)

vec1 + vec2 # c(5, 7, 9)

vec1 * vec2 # c(4, 10, 18)

vec1 / 2    # c(0.5, 1.0, 1.5) (scalar recycling)

# Vector recycling: When operations are performed on vectors of different lengths,

# R "recycles" the shorter vector. If the longer vector's length is not a

   multiple of the shorter vector's length, R will issue a warning.

vec3 <- c(10, 20, 30, 40, 50)

vec4 <- c(1, 2)

vec3 + vec4 # c(11, 22, 31, 42, 51) (vec4 is recycled: 1, 2, 1, 2, 1)

Note: Warning message will typically appear: "longer object length is not a multiple of shorter object length"

# Order of operations (PEMDAS/BODMAS applies)

(5 + 3) * 2 / 4 - 1 # (8 * 2 / 4) - 1 = (16 / 4) - 1 = 4 - 1 = 3

2. Modulo Operator in R

The modulo operator (%%) returns the remainder of a division. It's particularly useful for determining if a number is even or odd, cycling through values or performing operations based on remainders.

Syntax:

x %% y

Where       x: The dividend.

            y: The divisor.

# Positive numbers

10 %% 3   # 1 (10 divided by 3 is 3 with a remainder of 1)

15 %% 5   # 0 (15 is perfectly divisible by 5)

7 %% 2    # 1 (odd number)

8 %% 2    # 0 (even number)

# Negative numbers

-10 %% 3  # -1 (remainder has the same sign as the dividend -10)

10 %% -3  # 1 (remainder has the same sign as the dividend 10)

-10 %% -3 # -1 (remainder has the same sign as the dividend -10)


3. Integer Quotients in R

The integer quotient (or integer division) gives you the whole number part of a division, discarding any remainder. In R, this is achieved using the %/% operator. The sign of the result of %/% in R is determined by the standard rules of division.

Syntax:

            x %/% y

Where    x: The dividend.

           y: The divisor.

# Positive numbers

10 %/% 3  # 3 (10 divided by 3 is 3 with some remainder)

15 %/% 5  # 3

7 %/% 2   # 3

# Negative numbers

-10 %/% 3 # -4 (result is -3.33, rounded towards negative infinity)

10 %/% -3 # -4 (result is -3.33, rounded towards negative infinity)

-10 %/% -3 # 3 (result is 3.33, integer part is 3)


4) Relational (Comparison) Operators: 

Relational operators are used to comparing values, result is a logical (TRUE/FALSE).

  Equal to ( == ) ; 

  Not equal to ( != ) ; 

  Greater than ( >) ;  

  Less than (<) ;      

  Greater than or equal to (>=) ; 

  Less than or equal to (<=) ; 

# Relational Operators
x <- 7
y <- 5
x == y   # FALSE
x != y   # TRUE
x > y    # TRUE
x <= y   # FALSE

5) Logical Operators: 

Logical operators are used to perform logical operations on Boolean values. They are commonly used in control structures and conditional statements.

   Element-wise AND (&); Example: TRUE & FALSE

   Element-wise OR (|); Example: 
    
    Logical NOT (negation) (!); Example: ! TRUE
 
    Logical AND (&&) - evaluates only the first element, typically for single conditions in if statements)
 
    Logical OR (||); - evaluates only the first element, typical single conditions in if statements)

# Logical Operators
p <- TRUE
q <- FALSE
p & q    # FALSE (element-wise AND)
p | q    # TRUE (element-wise OR)
!p       # FALSE (NOT p)

# Vectorized logical operations
vec_a <- c(TRUE, FALSE, TRUE)
vec_b <- c(FALSE, TRUE, TRUE)
vec_a & vec_b # c(FALSE, FALSE, TRUE)

# Short-circuiting logical operators (for single conditions)
# Used typically in if/while conditions
if (10 > 5 && 20 < 10) { # 20 < 10 is not evaluated because 10 > 5 is TRUE 

6) Assignment Operators: 

Left assignment operator (<-): 

This is the preferred and most common assignment operator in R. 
        x<-10

Equal sign operator (=): 

Also works for assignment, but <- is generally recommended for clarity and to avoid confusion with the equality operator (==).
           x=10 

Rightward assignment operator (->): 

Less common, assigns the value on the left to the variable on the right.
            10 >-y

# Using the preferred assignment operator <-
my_variable <- 10
print(my_variable) # Output: 10

# Using = (also works)
another_variable = "Hello R!"
print(another_variable) # Output: "Hello R!"

# Rightward assignment (less common)
3.14 -> pi_value
print(pi_value) # Output: 3.14

7) Special / Miscellaneous Operators:
Special operators in R have unique function, particularly, when working with complex data structures

Sequence operator (:): creates a sequence of numbers
(e.g., 1:5 creates c(1, 2, 3, 4, 5))
        
Membership operator (%in%)- check if an element is an vector
Example: 3%in%c(1,2,3,4)    # TRUE
"apple" %in% c("banana", "apple", "orange") # TRUE

Matrix multiplication (%*%) - matrix multiplication operator

Integers in R

a) Identifying Integers: 
R primarily uses double-precision floating-point numbers (numeric) by default for most numerical values. To explicitly define an integer, you append an L suffix to the number.
  • Numbers without L are usually numeric (double).

  • Integers are stored more efficiently in memory and can be important for certain operations (e.g., indexing, specific C-level interfaces).

  • Type checking can be done with typeof() and class().

Example:     x<-5L    #Integer
                  y<-5      # Numeric (Double)
Note: For checking if a variable is an integer or not; one can use the  is.integer() function
is.integer(x); # TRUE
is.integer(y); # FALSE

b) Creating Integers

1. Directly use L suffix to specify integer directly ex: x<-5L
2. Converting other data type by using as.integer() function.

c) Integer operations

Integers in R behave similarly to numeric values in arithmetic, but the result may default to numeric if an operation involves a non-integer or if the result cannot be stored as an integer.

Example:

a <- 10L

b <- 3L

sum_ab <- a + b      # Integer addition: 13 (integer)

div_ab <- a / b      # Division: 3.333 (numeric, not integer)

int_div <- a %/% b   # Integer quotient: 3 (integer)

mod_ab <- a %% b     # Modulo (remainder): 1 (integer)

d) Integer limits

R integers are 32-bit, which means that it ranges from approximately -2.1 billion to 2.1 billion. Values outside this range will automatically be converted to numeric (double) to accommodate larger or smaller values.

Example:

int_max <- .Machine$integer.max  # Maximum integer value: 2147483647

is.integer(int_max)  # TRUE

# Going beyond integer limit

large_value <- as.integer(int_max + 1)

is.integer(large_value)  # FALSE, because it’s converted to numeric

Factors in R

R factor is used to store categorical data as levels. It can store both character and integer types of data. These factors are created with the help of factor() functions, by taking a vector as input.

R factors are variables. It takes a limited number of different values. Hence, those variables are often known as categorical variables. In order to categorise the data and store it on multiple levels, one can use the data object called R factor. They can store both strings and integers. They are also useful in the columns which have a limited number of unique values.

The factor is stored as integers. They have labels associated with these unique integers. One need to be careful while treating factors like strings. Factor contains a predefined set value called levels. By default, R always sorts levels in alphabetical order.

Factors in R



Attributes of a Factor

Some important attributes of the factor that we will use in this article are:

  • x: The input vector that is to be transformed into a vector.
  • levels: This is an optional vector that represents a set of unique values that are taken by x.
  • labels: It is a character vector that corresponds to the number of labels.
  • Exclude: With this attribute, one can specify the values to be excluded.
  • ordered: This is a logical attribute that determines if the levels should be ordered.
  • nmax: This attribute specifies the upper bound for the maximum number of levels.

i) Create an R Factor

In order to create first R factor, one makes use of the factor() function.

To create factor, first we create a vector called ‘directions’ that holds the direction “North”, “West” and “South”. Notice how “East” is absent from this vector.


Notice that in the output, we have three levels “North”, “South” and “West”. This does not contain the redundant “North” that was occurring twice in our input vector.

In order to add this missing level to our factors, one can use the “levels” attribute as follows:

Syntax:

  factor(directions, levels=c("North","East","West","South"))

Output: 

        [1] North North West South

    Levels: North East West South


In order to provide abbreviations or ‘labels’ to our levels, one makes use of the labels argument as follows 

Syntax:

factor(directions,levels=c("North","East","West","South"),labels=c("N","E","W","S"))

Output: 

        [1] N N W S

    Levels: N E W S

Finally, if you want to exclude any level from your factor, you can make use of the exclude argument. For example, let us exclude “North” from the list of levels. In order to do so, we initialize exclude with “North”.

Syntax:

    factor(directions, levels= c("North", "East", "South", "West"), exclude = "North")

Output: 

       [1] <NA> <NA> West South

    Levels: East South West

ii) Generate Factor Level in R

In order to generate factor levels in R, one make use of the gl() function. The syntax for generating factor is gl(n, k, labels) where n is an integer specifying the number of levels.

  • k is an integer that gives out a number of replications.
  • And, labels are simply the vector of labels for our factor.

Syntax:

             BigData <- gl(3, 2, labels = c("Hadoop","Spark","Flink"))

        print(BigData)

Output: 

        [1] Hadoop Hadoop Spark  Spark  Flink  Flink 
        Levels: Hadoop Spark Flink


iii) Accessing Components of Factor in R

Let us first create a factor “data” as follows:

Syntax:

    compass <- c("East","West","South","North")
    data <- factor(compass)     data

Output: 

    [1] East West South North

   Levels: East North South West

There are various ways to access the elements of a factor in R. Some of the ways are as follows:

data[4] #Accessing the 4th element
[1] North
Levels: East North South West
data[c(2,3)] #Accessing the 2nd & 3rd element
[1] West  South
Levels: East North South West
data[-1] #Accessing everything except 1st element
[1] West  South North
Levels: East North South West
data[c(TRUE, FALSE, TRUE, TRUE)]
[1] East  South North
Levels: East North South West  #Accessing using Logical Vector


iv) Modify an R Factor

To modify a factor, we are only limited to the values that are not outside the predefined levels.

Example- 

data[2] ="North" #Modifying 2nd element
data[3] ="Moon" #Cannot Modify Factor with an Element outside its scope
data[2]
[1] North
Levels: East North South West

In `[<-In `[<-.factor`(`*tmp*`, 3, value = "Moon") :
invalid factor level, NA generated


v) Factor Functions in R

Some of these functions; is.factor(), as.factor(), is.ordered(), as.ordered(). is.factor() checks if the input is present in the form of factor and returns a Boolean value (TRUE or FALSE). 

as.factor() takes the input (usually a vector) and converts it into a factor. It takes an unordered function and returns a factor that is arranged in order.

is.ordered() checks if the factor is ordered and returns boolean TRUE or FALSE. 

Example- 

f_directions <- factor(directions)
> is.factor(f_directions)                     
[1] TRUE
> as.factor(directions)                     
[1] North North West  South
Levels: North South West
> is.ordered(f_directions)                    
[1] FALSE
> as.ordered(f_directions)
[1] North North West  South
Levels: North < South < West


Control Structures in R

In order to control the execution of the expressions flow in R, we make use of the control structures. These control structures are also called as loops in R. There are eight types of control structures in R:

  • if
  • if-else
  • for
  • nested loops
  • while
  • repeat and break
  • next
  • return


1. if Condition in R

This task is carried out only if this condition is returned as TRUE. R makes it even easier: You can drop the word then and specify your choice in an if statement.

Example: The if statement executes code only if a specified condition is TRUE.

x <- 5
if (x > 3) {
  print("x is greater than 3")
}

2. if-else Condition in R

An if…else statement contains the same elements as an if statement, with some extra elements:

  • The keyword else, placed after the first code block.
  • The second block of code, contained within braces, that has to be carried out, only if the result of the condition in the if() statement is FALSE.

Syntax:

if (test_expression) { statement } else { statement }

Example:


val1 = 10 #Creating our first variable val1
val2 = 5 #Creating second variable val2 if(val1>val2) {
print("Value 1 is greater than Value 2") # Executing Condition
} else if (val1 < val2){
print("Value 1 is less than Value 2")
} Output:
[1] "Value 1 is greater than Value 2"

3. for Loop in R

A loop is a sequence of instructions that is repeated until a certain condition is reached. for, while and repeat, with the additional clauses break and next are used to construct loops.

Example:

These control structures in R, made of the rectangular box ‘init’ and the diamond. It is executed a known number of times. for is a block that is contained within curly braces.

values <- c(1,2,3,4,5) for(id in 1:5){ print(values[id]) }

Output: 
[1] 1
[1] 2
[1] 3
[1] 4
[1] 5

4. Nested Loop in R

It is similar to the standard for loop, which makes it easy to convert for loop to a foreach loop. Unlike many parallel programming packages for R, foreach doesn’t require the body of for loop to be turned into a function. One can call this a nesting operator because it is used to create nested foreach loops.

Example-
mat <- matrix(1:10, 2) for (id1 in seq(nrow(mat))) { for (id2 in seq(ncol(mat))) { print(mat[id1, id2]) } }

Output: 
[1] 1
[1] 3
[1] 5
[1] 7
[1] 9
[1] 2
[1] 4
[1] 6
[1] 8
[1] 10


5. while Loop in R

The format is while(cond) expr, where cond is the condition to test and expr is an expression.

R would complain about the missing expression that was supposed to provide the required True or False and in fact, it does not know ‘response’ before using it in the loop. We can also do this because, if we answer right at first attempt, the loop will not be executed at all.

Example-
val = 2.987 while(val <= 4.987) { val = val + 0.987 print(c(val,val-2,val-1)) }
Out put

[1] 3.974 1.974 2.974
[1] 4.961 2.961 3.961
[1] 5.948 3.948 4.948

6) repeat and break Statement in R

One use break statement inside a loop (repeat, for, while) to stop the iterations and flow the control outside of the loop. While in a nested looping situation, where there is a loop inside another loop, this statement exits from the innermost loop that is being evaluated.

A repeat loop is used to iterate over a block of code, multiple numbers of times. There is no condition check in a repeat loop to exit the loop. One put a condition explicitly inside the body of the loop and use the break statement to exit the loop. Failing to do so will result in an infinite loop.

Syntax

repeat { # simulations; generate some value have an expectation if within some range, # then exit the loop if ((value - expectation) <= threshold) { break } }

The repeat loop is an infinite loop and is used in association with a break statement.

Example:

Below, the code shows a repeat statement in R:

A break statement is used in a loop to stop the iterations and flow the control outside of the loop.

Example of Repeat Statement in R:

val <- 5 repeat { print(val) val <- val+1 if (val == 10){ break } Out put:

[1] 5
[1] 6
[1] 7
[1] 8
[1] 9


Example of Break Statement in R:

values = 1:10 for (id in values){ if (id == 2){ break } print(id) }

Out put 

[1] 1


7. next Statement in R

next jumps to the next cycle without completing a particular iteration. In fact, it jumps to the evaluation of the condition holding the current loop. Next statement enables to skip the current iteration of a loop without terminating it.

Example:

x = 1: 4 for (i in x) { if (i == 2) { next } print(i) }

Out-put

[1] 1
[1] 3
[1] 4

8. return Statement in R

Many times, we will require some functions to do processing and return back the 

result. This is accomplished with the return() statement in R.

Syntax:

return(expression)

Example:

check <- function(x) { if (x > 0) { result <- "Positive" } else if (x < 0) { result <- "Negative" } else { result <- "Zero" } return(result) }

check(10)

[1] "Positive"

check(-10)

[1] "Negative"

check(0)

[1] "Zero"


Functions in R

A set of statements which are organized together to perform a specific task is
known as function. R provides a series in-built function, and it allows the user to

create their own functions. Functions are used to perform tasks in the modular

approach.

Functions are used to avoid repeating the same task and to reduce complexity.

To understand and maintain code, we logically break it into smaller parts

using the function. A function should be


  1. Written to carry out a specified task.
  2. May or may not have arguments
  3. Contain a body in which code is written.
  4. May or may not return one or more output values.

Why Use Functions?

    • Reusability: Write once, use multiple times.
    • Modularity: Break complex tasks into manageable units.
    • Maintainability:
                    Easier to debug and modify.
    • Readability     
                Makes the code easier to understand    
    • Flexibility
                    Simplifies the addition of new features

Basic Syntax

function_name <- function(arguments) {

  # Body of the function
  # Perform calculations or operations
  return(output)  # Optional
}

Example

# A function to add two numbers

add_numbers <- function(a, b) {
  result <- a + b
  return(result)
}
# Calling the function
add_numbers(5, 3)  # Output: 8

Components of a Function


  1. Function Name: Identifier used to call the function.
  2. Arguments: Inputs passed to the function for processing.
  3. Body: Code block containing the logic of the function.
  4. Return Statement: Specifies the output (optional, as R implicitly returns the last evaluated expression).

Types of Functions

  1. Built-In Functions:

    The functions which are already created or defined in the programming framework are known as built-in
    functions. User doesn't need to create these types of functions, and these
    functions are built into an application. End-users can access these functions
    by simply calling it. R have different types of built-in functions such as
    seq(), mean(), max(), and sum(x) etc.

  2. User-Defined

    R allows to create our own function in our program. A user defines a user-define function to
    fulfill the requirement of user. Once these functions are created, one can use
    these functions like in-built function.

  3. Anonymous Functions: Functions without a name, often used in short-lived tasks.
  4. Examples- 
    # Apply a lambda function to a vector
    squared <- sapply(1:5, function(x) x^2)   # Output: 1, 4, 9, 16, 25
    # Function to calculate factorial
    factorial <- function(n) {
      if (n == 0) return(1)
      return(n * factorial(n - 1))
    }
    factorial(5)  # Output: 120

Scooping Rule: 
Scoping rules determine how R looks for the value of a variable. 
Lexical Scoping
R uses lexical scoping (also known as static scoping). 
This means that the environment where a function was defined 
(its parent environment). If not found, R searches the parent environments
recursively until the global environment.

Example

x <- 10
outer_function <- function() {
  x <- 5  # Local variable
  inner_function <- function() {
    x + 1  # Resolves to local x in outer_function
  }
  inner_function()
}
outer_function()  # Output: 6
x  # Output: 10 (global x remains unchanged)

Dates and Times in R

R has powerful capabilities for handling dates and times using various classes.

Common Classes:

  • Date: Represents dates (year, month, day).

  • POSIXct: Represents dates and times, stored as seconds since the Unix epoch (January 1, 1970, 00:00:00 UTC). More efficient for calculations.

  • POSIXlt: Represents dates and times as a list of components (year, month, day, hour, minute, second). Easier for extracting individual components.

Key Functions:

  • Sys.Date(): Get the current date.

  • Sys.time(): Get the current date and time.

  • as.Date(): Convert to Date class.

  • as.POSIXct(): Convert to POSIXct class.

  • as.POSIXlt(): Convert to POSIXlt class.

  • format(): Format dates/times into specific character strings.

  • strptime(): Parse character strings into POSIXlt objects (useful for specific formats).

  • difftime(): Calculate time differences.

  • lubridate package: Highly recommended for advanced date/time manipulation.

Example:

datetime <- as.POSIXct("2024-12-04 10:00:00")
formatted <- format(datetime, "%Y-%m-%d %H:%M:%S")  # Output: "2024-12-04 10:00:00"
For Practice:

# Current Date and Time
current_date <- Sys.Date()
print(current_date)
print(class(current_date)) # "Date" current_time_ct <- Sys.time()
print(current_time_ct)
print(class(current_time_ct)) # "POSIXct" "POSIXt" # Converting character strings to Date/POSIXct
date_string <- "2023-10-26"
my_date <- as.Date(date_string)
print(my_date) datetime_string <- "2023-10-26 14:30:00"
my_datetime_ct <- as.POSIXct(datetime_string)
print(my_datetime_ct) # Specifying format for conversion
custom_format_date_string <- "26/10/2023"
my_custom_date <- as.Date(custom_format_date_string, format = "%d/%m/%Y")
print(my_custom_date) custom_format_datetime_string <- "Oct 26, 2023 2:30 PM"
my_custom_datetime_ct <- as.POSIXct(custom_format_datetime_string,
format = "%b %d, %Y %I:%M %p")
print(my_custom_datetime_ct) # Formatting dates/times into strings
formatted_date <- format(my_date, "%A, %B %d, %Y")
print(formatted_date) # e.g., "Thursday, October 26, 2023" formatted_time <- format(my_datetime_ct, "%I:%M %p (%Z)")
print(formatted_time) # e.g., "02:30 PM (IST)" # Date arithmetic
date1 <- as.Date("2023-01-01")
date2 <- as.Date("2023-01-10")
diff_days <- date2 - date1
print(diff_days) # Time difference of 9 days # Adding/subtracting time units
future_date <- my_date + 7 # Adds 7 days
print(future_date) # POSIXlt for component extraction
my_datetime_lt <- as.POSIXlt(my_datetime_ct)
print(my_datetime_lt$year + 1900) # Years since 1900
print(my_datetime_lt$mon + 1) # Months (0-indexed)
print(my_datetime_lt$hour)


Comments

Popular posts from this blog

Unit-5

Unit-2