0% found this document useful (0 votes)
2 views29 pages

Introduction To R

Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views29 pages

Introduction To R

Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

R-Programming

R is a programming language and software environment specifically designed for statistical


analysis, data visualization, and data science. It is widely used among statisticians, data
scientists, and researchers for tasks that involve:
 Statistical computing: Performing various types of statistical tests, modeling, and
inferential analysis.
 Data manipulation: Cleaning, transforming, and analyzing datasets efficiently.
 Data visualization: Creating graphs and plots, including histograms, scatter plots,
and advanced graphics, to help interpret data findings.

It is also open-source, meaning it is free to use and widely supported by a community of


developers and data analysts. R generally comes with the Command-line interface. R is
available across widely used platforms like Windows, Linux, and macOS. Also, the R
programming language is the latest cutting-edge tool.

It was designed by Ross Ihaka and Robert Gentleman at the University of Auckland, New
Zealand, and is currently developed by the R Development Core Team. R programming
language is an implementation of the S programming language. It also combines with lexical
scoping semantics inspired by Scheme. Moreover, the project conceives in 1992, with an
initial version released in 1995 and a stable beta version in 2000.
R is a programming language and software environment for statistical analysis, graphics
representation and reporting. R was created by Ross Ihaka and Robert Gentleman at the
University of Auckland, New Zealand, and is currently developed by the R Development
Core Team. R is freely available under the GNU General Public License, and pre-compiled
binary versions are provided for various operating systems like Linux, Windows and Mac.
This programming language was named R, based on the first letter of first name of the two R
authors (Robert Gentleman and Ross Ihaka), and partly a play on the name of the Bell Labs
Language S. ([Link]

What is the R programming language used for?

The R programming language is used for statistical analysis, data


visualization, and data science. It’s popular among researchers, data
scientists, and statisticians for its powerful tools and packages.

What is R Programming?

R is one of the most popular statistical programming languages. For statisticians it was
created and it is the predecessor of the S language. However, it is now commonly used in
statistical computing and graphics. R can also be used with other programming languages.
Also, R programming allows you to debug other programming codes. In 1995, R officially
released for public use. But firstly, it was released in 1985. And R programming takes its
name from Ross Ihala and Robert Gentleman’s initials who are the creators or developers of
the R programming language. R programming was created at the University of Auckland.
Using R, statisticians may readily do complex statistical analysis.
Why R Programming Language?

 R programming is used as a leading tool for machine learning, statistics, and data
analysis. Objects, functions, and packages can easily be created by R.
 It’s a platform-independent language. This means it can be applied to all operating
system.
 It’s an open-source free language. That means anyone can install it in any
organization without purchasing a license.
 R programming language is not only a statistic package but also allows us to integrate
with other languages (C, C++). Thus, you can easily interact with many data sources
and statistical packages.
 The R programming language has a vast community of users and it’s growing day by
day.
 R is currently one of the most requested programming languages in the Data Science
job market that makes it the hottest trend nowadays.
Why is R considered a good software for statistical problems?
Because it was first designed by statisticians for statistical purposes, R is exceptionally
well-suited to data science, an important field in today's world. While R's core function is
statistical analysis and graphics, its use extends past these and into AI, machine learning,
financial analysis, and more

What are the benefits of R in Excel?

Understanding R programming over Excel for Data Analysis

 R can handle very large datasets. ...


 R can automate and calculate much faster than Excel. ...
 R source code is reproducible. ...
 Community libraries worth of R source code are available to all. ...
 R is free, Excel is not

The source code of R can be used repeatedly and with different data sets in ways that
Excel formulas cannot. R clearly shows the code (instructions), data and columns used for
an analysis in ways that Excel does no
Why use R instead of SPSS?

R offers much more opportunities to customize and optimize graphs due to the wide
range of available modules. The most widely used module in R is ggplot2. These graphs are
also easily made interactive, which allows users to play with data. The graphical capabilities
of SPSS are purely functional. R provides a vast library of built-in functions and packages
(like `dplyr`, `ggplot2`, and `caret`) that extend its capabilities, making it powerful for data
analysis and machine learning.

Key Differences Between R vs SPSS

WINDOWS POWERSHELL Course Bundle - 7 Courses in 1


26+ Hours of HD Videos | 7 Courses | Verifiable Certificate of Completion | Lifetime Access
4.5

Below are the most important key differences between R vs SPSS:

 R is open-source, free software, where the R community is fast for software updates
adding new libraries regularly new version of stable R is 3.5. IBM SPSS is not free. If
someone wants to use SPSS software, it has to download the trial version first; due to
the cost-effectiveness of SPSS, most start-ups opt for R software.
 R is written in C and Fortran. R has stronger object-oriented programming facilities
than SPSS, whereas SPSS’s graphical user interface uses Java. It is mainly used for
interactively and statistical analysis.
 In statistical analysis decision trees, R does not provide many algorithms, and most of
the packages of R can only implement Classification and Regression Trees, and their
interface is not as user-friendly. On the other hand, Decision trees in IBM SPSS are
better than R because R does not offer many tree algorithms. For decision trees, the
SPSS interface is very user-friendly, understandable, and easy to use.
 R has a less interactive analytical tool than SPSS. Still, its editors are available to
provide GUI support for programming in R. R is the best tool for learning and
practicing hands-on analytics, as it helps the analyst master the various analytics steps
and commands. Moreover, the SPSS interface is more or less similar to an Excel
spreadsheet.
 R offers much more opportunities to modify and optimize graphs due to the wide
range of available packages. The most widely used package in R is ggplot2 and R
shiny. Users can easily make graphs interactive in R, which enables them to
manipulate data. In SPSS, graphs are less interactive than in R, where you can create
only basic and simple graphs or charts. Data management in both R and SPSS is
almost the same. A significant drawback of R is that most functions load all the data
into memory before execution. In contrast, SPSS provides data management functions
such as sorting, aggregation, transposition, and merging of the table.

R vs SPSS Comparison Table

Below is the comparison table of R vs SPSS:

Basis for
R SPSS
Comparison
User Interface R has the less interactive SPSS has a more interactive
analytical tool, but editors are and user-friendly interface.
available to provide GUI support SPSS displays data in a
for programming in R. R is the spreadsheet-like fashion.
best tool for learning and
practicing hands-on analytics, as
it helps the analyst master the
various analytics steps and
commands.
For decision trees, R does not
For Decision trees, IBM SPSS
offer many algorithms. Most of
is better than R because R does
the packages of R can only
not offer many tree algorithms.
Decision Making implement CART
For decision trees, the SPSS
(Classification and Regression
interface is very user-friendly
Tree), and their interface is not
and understandable.
as user-friendly.
In data management, IBM
A significant drawback of R is
SPSS is more or less similar to
that most of its functions have to
R. It provides data management
Data Management load all the data into memory
functions such as sorting,
before execution, which limits
aggregation, transposition, and
the volumes that can be handled.
merging of the table.
In terms of documentation, R
has readily available explain
While SPSS is lagging in this
documentation files. R
Documentation feature, SPSS lacks this feature
community, however, is one of
due to its limited use.
the strongest open-source
communities.
R is written in C and Fortran. R The graphical user interface
has stronger object-oriented (GUI) of SPSS is written in
Platform programming facilities than Java and primarily used for
most statistical computing interactive and statistical
languages. analysis.
R is open-source, free software, IBM SPSS is not free. If
where the R community is very someone wants to learn SPSS,
Cost
fast for software updates and they must use the trial version
adding new libraries. first.
R offers much more
The graphical capabilities of
opportunities to customize and
SPSS are purely functional.
optimize graphs due to the wide
However, it is possible to make
range of available modules. The
Visualizations minor changes to the graph;
most widely used module in R is
fully customizing your graph
ggplot2. These graphs are also
and visualizations in SPSS can
easily made interactive, which
be very cumbersome.
allows users to play with data.

Why use R instead of Stata?


R is an open-source programming language. R has a more difficult learning curve, but it is
far more powerful and adaptable. R has a lot of features that Stata doesn't have, basically,
there is nothing in stata that you can't do in R. R is also a good starting point for other
programming languages like Python.
R has better visualizations. Once you have a good handle on ggplot2, you can do pretty
amazing things with almost any type of data. I've found R easier for writing custom packages
and functions. R is closer to the stats/machine learning community so you'll find more
support/packages than Stata.

Advantages of R:

 R is the most comprehensive statistical analysis package. As new technology and


concepts often appear first in R.
 As R programming language is an open source. Thus, you can run R anywhere and at
any time.
 R programming language is suitable for GNU/Linux and Windows operating system.
 R programming is cross-platform which runs on any operating system.
 In R, everyone is welcome to provide new packages, bug fixes, and code
enhancements.

Disadvantages of R:

 In the R programming language, the standard of some packages is less than perfect.
 Although, R commands give little pressure to memory management. So R
programming language may consume all available memory.
 In R basically, nobody to complain if something doesn’t work.
 R programming language is much slower than other programming languages such as
Python and MATLAB.

Applications of R:

 We use R for Data Science. It gives us a broad variety of libraries related to statistics.
It also provides the environment for statistical computing and design.
 R is used by many quantitative analysts as its programming tool. Thus, it helps in data
importing and cleaning.
 R is the most prevalent language. So many data analysts and research programmers
use it. Hence, it is used as a fundamental tool for finance.
 Tech giants like Google, Facebook, bing, Twitter, Accenture, Wipro and many more
using R nowadays.
An R operator is a symbol or a combination of symbols used to perform specific operations on one
or more variables or values.

The R Language stands out as a powerful tool in the modern era of statistical computing and
data analysis. Widely embraced by statisticians, data scientists, and researchers, the R
Language offers an extensive suite of packages and libraries tailored for data manipulation,
statistical modeling, and visualization. In this article, we explore the features, benefits, and
applications of the R Programming Language, shedding light on why it has become an
indispensable asset for data-driven professionals across various industries.

R programming language is an implementation of the S programming language. It also


combines with lexical scoping semantics inspired by Scheme. Moreover, the project was
conceived in 1992, with an initial version released in 1995 and a stable beta version in 2000.
R Programming Language

What is R Programming Language?

R programming is a leading tool for machine learning, statistics, and data analysis, allowing
for the easy creation of objects, functions, and packages. Designed by Ross Ihaka and Robert
Gentleman at the University of Auckland and developed by the R Development Core Team,
R Language is platform-independent and open-source, making it accessible for use across all
operating systems without licensing costs. Beyond its capabilities as a statistical package, R
integrates with other languages like C and C++, facilitating interaction with various data
sources and statistical tools. With a growing community of users and high demand in the
Data Science job market, R is one of the most sought-after programming languages today.
Originating as an implementation of the S programming language with influences from
Scheme, R has evolved since its conception in 1992, with its first stable beta version released
in 2000.

Why Use R Language?

The R Language is a powerful tool widely used for data analysis, statistical computing, and
machine learning. Here are several reasons why professionals across various fields prefer R:

1. Comprehensive Statistical Analysis:

 R language is specifically designed for statistical analysis and provides a vast array of
statistical techniques and tests, making it ideal for data-driven research.

2. Extensive Packages and Libraries:


 The R Language boasts a rich ecosystem of packages and libraries that extend its capabilities,
allowing users to perform advanced data manipulation, visualization, and machine learning
tasks with ease.

3. Strong Data Visualization Capabilities:

 R language excels in data visualization, offering powerful tools like ggplot2 and plotly, which
enable the creation of detailed and aesthetically pleasing graphs and plots.

4. Open Source and Free:

 As an open-source language, R is free to use, which makes it accessible to everyone, from


individual researchers to large organizations, without the need for costly licenses.

5. Platform Independence:

 The R Language is platform-independent, meaning it can run on various operating systems,


including Windows, macOS, and Linux, providing flexibility in development environments.

6. Integration with Other Languages:

 R can easily integrate with other programming languages such as C, C++, Python, and Java,
allowing for seamless interaction with different data sources and statistical packages.

7. Growing Community and Support:

 R language has a large and active community of users and developers who contribute to its
continuous improvement and provide extensive support through forums, mailing lists, and
online resources.

8. High Demand in Data Science:

 R is one of the most requested programming languages in the Data Science job market,
making it a valuable skill for professionals looking to advance their careers in this field.

Features of R Programming Language

The R Language is renowned for its extensive features that make it a powerful tool for data
analysis, statistical computing, and visualization. Here are some of the key features of R:

1. Comprehensive Statistical Analysis:

 R langauge provides a wide array of statistical techniques, including linear and nonlinear
modeling, classical statistical tests, time-series analysis, classification, and clustering.

2. Advanced Data Visualization:

 With packages like ggplot2, plotly, and lattice, R excels at creating complex and aesthetically
pleasing data visualizations, including plots, graphs, and charts.
3. Extensive Packages and Libraries:

 The Comprehensive R Archive Network (CRAN) hosts thousands of packages that extend R’s
capabilities in areas such as machine learning, data manipulation, bioinformatics, and more.

4. Open Source and Free:

 R is free to download and use, making it accessible to everyone. Its open-source nature
encourages community contributions and continuous improvement.

5. Platform Independence:

 R is platform-independent, running on various operating systems, including Windows,


macOS, and Linux, which ensures flexibility and ease of use across different environments.

6. Integration with Other Languages:

 R language can integrate with other programming languages such as C, C++, Python, Java,
and SQL, allowing for seamless interaction with various data sources and computational
processes.

7. Powerful Data Handling and Storage:

 R efficiently handles and stores data, supporting various data types and structures, including
vectors, matrices, data frames, and lists.

8. Robust Community and Support:

 R has a vibrant and active community that provides extensive support through forums,
mailing lists, and online resources, contributing to its rich ecosystem of packages and
documentation.

9. Interactive Development Environment (IDE):

 RStudio, the most popular IDE for R, offers a user-friendly interface with features like syntax
highlighting, code completion, and integrated tools for plotting, history, and debugging.

10. Reproducible Research:

 R supports reproducible research practices with tools like R Markdown and Knitr, enabling
users to create dynamic reports, presentations, and documents that combine code, text, and
visualizations.

Advantages of R language

 R is the most comprehensive statistical analysis package. As new technology and concepts
often appear first in R.
 As R programming language is an open source. Thus, you can run R anywhere and at any
time.

 R programming language is suitable for GNU/Linux and Windows operating systems.

 R programming is cross-platform and runs on any operating system.

 In R, everyone is welcome to provide new packages, bug fixes, and code enhancements.

Disadvantages of R language

 In the R programming language, the standard of some packages is less than perfect.

 Although, R commands give little pressure on memory management. So R programming


language may consume all available memory.

 In R basically, nobody to complain if something doesn’t work.

 R programming language is much slower than other programming languages such as Python
and MATLAB.

Applications of R language

 We use R for Data Science. It gives us a broad variety of libraries related to statistics. It also
provides the environment for statistical computing and design.

 R is used by many quantitative analysts as its programming tool. Thus, it helps in data
importing and cleaning.

 R is the most prevalent language. So many data analysts and research programmers use it.
Hence, it is used as a fundamental tool for finance.

 Tech giants like Google, Facebook, Bing, Twitter, Accenture, Wipro, and many more using R
nowadays.

Conclusion

In conclusion, the R programming language stands out as an essential tool for data analysis,
statistical computing, and visualization. Its comprehensive range of statistical techniques,
advanced data visualization capabilities, and extensive package ecosystem make it a preferred
choice for data scientists, statisticians, and researchers. As an open-source, platform-
independent language, R provides accessibility and flexibility, while its ability to integrate
with other programming languages enhances its versatility. The robust support from its
growing community further enriches its utility, making R a valuable asset in the data science
landscape. Embracing the R programming language empowers professionals to leverage
data effectively, driving informed decisions and fostering innovation across various fields.
R Programming Language – FAQs

What is the R programming language used for?

The R programming language is used for statistical analysis, data visualization, and data
science. It’s popular among researchers, data scientists, and statisticians for its powerful tools
and packages.

How do I install R and RStudio?

Install R from the CRAN website by selecting the appropriate version for your OS, then
download and install RStudio from its official website to get a user-friendly IDE for R.

What are some essential packages in R?

Essential R packages include ggplot2 for visualization, dplyr for data manipulation, tidyr for
data tidying, caret for machine learning, and shiny for building interactive web applications.

How can I learn R programming effectively?

Learn R through online courses (Coursera, edX, DataCamp), tutorials, and hands-on practice
with real-world projects. Utilize free resources like blogs, forums, and YouTube for
additional guidance.

What are the advantages of using R over other programming languages?

R specializes in statistics and data visualization, offers a vast package ecosystem, is open-
source and free, runs on various OS platforms, and has strong community support

R Operators
Operators

An R operator is a symbol or a combination of symbols that direct the compiler to perform


specific operations on one or more variables or values. Operators in R are essential for tasks
like arithmetic calculations, logical comparisons, data manipulation, and assignments.
Operators simulate the various mathematical, logical, and decision operations performed on a
set of Complex Numbers, Integers, and Numericals as input operands.

Types of the operator in R language


 Arithmetic Operators
 Assignment Operators

 Relational Operators/Comparison Operators
 Logical Operators
 Miscellaneous Operators

Operators in R can be organized into the following groups:


([Link]
fbclid=IwY2xjawGlJWVleHRuA2FlbQIxMAABHf6ky3UOWP0LVraakwE_rXlES1GrKStf
FNh7yVNETQkrqs2P86EDI2oHzg_aem_N38YfECPlh2vT71VVpQRbw)

 Arithmetic operators for traditional mathematical evaluations such as addition and


subtraction.
 Assignment operators for assigning values to variables.
 Comparison operators for testing equality between values.
 Logical operators for evaluating the “truthiness” of values against one another.
 Miscellaneous operators for various tasks including vectors and sequencing.

Arithmetic operators

R supports the following arithmetic operators:

 Addition, +, which returns the sum of two numbers.


 Subtraction, -, which returns the difference between two numbers.
 Multiplication, *, which returns the product of two numbers.
 Division, /, which returns the quotient of two numbers.
 Exponents, ^, which returns the value of one number raised to the power of another.
 Modulus, %%, which returns the remainder of one number divided by another.
 Integer Division, %/%, which returns the integer quotient of two numbers.

Assignment operators

R uses the following assignment operators:

 <- assigns a value to a variable from right to left.


 -> assigns a value to a variable left to right.
 <<- is a global version of <-.
 ->> is a global version of ->.
 = works the same way as <-, but its use is discouraged.

### Explanation and Examples of R Assignment Operators

1. **`<-`**: This operator assigns a value to a variable from right to left.

- **Example**:

x <- 10 # Assigns the value 10 to the variable x

- This is the most common and recommended way to assign values to variables in R.
2. **`->`**: This operator assigns a value to a variable from left to right.

- **Example**:

10 -> x # Assigns the value 10 to the variable x

- This operator is less commonly used but performs the same function as `<-`, just with
reversed direction.

3. **`<<-`**: This is the global assignment operator and is used to assign a value to a
variable in the global environment or the parent scope of the current environment.

- **Example**:

x <<- 20 # Assigns the value 20 to the variable x in the global environment

- **Use Case**: `<<-` is helpful when you want to modify a variable in a parent scope from
within a function, but it should be used cautiously, as it can unintentionally change global
variables and lead to unexpected behavior.

4. **`->>`**: This is the global version of the `->` operator, used to assign values globally
from left to right.

- **Example**:

20 ->> x # Assigns the value 20 to the variable x in the global environment

- Like `<<-`, `->>` is rarely used and should be handled with care.

5. **`=`**: This operator works similarly to `<-` for assignment but is often discouraged.

- **Example**:

y = 30 # Assigns the value 30 to the variable y

- **Why It's Discouraged**:

- `=` can sometimes lead to confusion when used in function arguments because R uses
`=` to specify named parameters in functions.

- Using `<-` provides a clearer distinction between assignment and specifying arguments.

- **Function Argument Example**:

mean(x = c(1, 2, 3, 4)) # Here, x is being specified as an argument to the mean function,
not a variable assignment

```
- If you use `=` inappropriately, it might result in unintended consequences, especially in
complex code structures where functions and variable assignments are mixed.

*Best Practice**: Use `<-` for assignment to avoid ambiguity and to follow conventional R
coding standards.

Comparison operators

R has the following comparison operators:

 Equal, ==, which returns TRUE if two values are equal.


 Not equal, !=, which returns TRUE if two values are not equal.
 Less than, <, which returns TRUE if left value is less than right value.
 Less than or equal to, <=, which returns TRUE if left value is less than or equal to right
value.
 Greater than, >, which returns TRUE if left value is greater than right value.
 Greater than or equal to, >=, which returns TRUE if left value is greater than or equal to
right value.

Your description of the relational operators in R is accurate and clearly stated. Here's a
refined and concise version:

### Relational Operators in R

Relational operators are used to compare two values, returning a logical value of `TRUE` or
`FALSE`:

1. **Equal (`==`)**: Returns `TRUE` if two values are equal.

- **Example**: `5 == 5` results in `TRUE`.

2. **Not equal (`!=`)**: Returns `TRUE` if two values are not equal.

- **Example**: `5 != 4` results in `TRUE`.

3. **Less than (`<`)**: Returns `TRUE` if the left value is less than the right value.

- **Example**: `3 < 5` results in `TRUE`.


4. **Less than or equal to (`<=`)**: Returns `TRUE` if the left value is less than or equal to
the right value.

- **Example**: `4 <= 4` results in `TRUE`.

5. **Greater than (`>`)**: Returns `TRUE` if the left value is greater than the right value.

- **Example**: `7 > 3` results in `TRUE`.

6. **Greater than or equal to (`>=`)**: Returns `TRUE` if the left value is greater than or
equal to the right value.

- **Example**: `6 >= 5` results in `TRUE`.

These operators are crucial for conditional statements, filtering data, and logical decision-
making in R.

Logical operators

R has the following logical operators:

 Element-wise AND, &, for comparing each element and returning TRUE if both
elements are TRUE.
 Logical AND, &&, which returns TRUE if both values are TRUE, only evaluates as many
elements as necessary.
 Element-wise OR, |, for comparing each element and returning TRUE if either element
is TRUE.
 Logical OR, ||, which returns TRUE if either value is TRUE, only evaluates as many
elements as necessary.
 Logical NOT, !, which returns TRUE if the associated statement is FALSE.

Note: The long form of AND and OR (&& and ||) are preferred for if statements as the short
form can produce a vector value.

Your description of logical operators in R is clear. Here’s an explanation along with


examples and clarification on the behavior of these operators:
### Logical Operators in R

1. **Element-wise AND (`&`)**: Compares each element of two vectors and returns `TRUE`
if both elements are `TRUE`(If both elements are true, then will be true otherwise false).

- **Example**:

c(TRUE, FALSE, TRUE) & c(TRUE, TRUE, FALSE

# Result: TRUE, FALSE, FALSE

- **Cause**: Each element of the vectors is compared individually.

2. **Logical AND (`&&`)**: Evaluates only the first element of each vector and returns
`TRUE` if both are `TRUE` (If both true, then will be true otherwise false and consider
only first element).

- **Example**:

c(TRUE, FALSE, TRUE) && c(TRUE, TRUE, FALSE)

# Result: TRUE

- **Cause**: `&&` is used for control flow and only evaluates the first elements, making it
efficient for logical comparisons where only the first value matters.

3. **Element-wise OR (`|`)**: Compares each element of two vectors and returns `TRUE` if
either element is `TRUE`. (Find first true any element either two vectors, then will be
true otherwise false).

- **Example**:

c(TRUE, FALSE, TRUE) | c(FALSE, TRUE, FALSE)

# Result: TRUE, TRUE, TRUE

c(TRUE, FALSE, TRUE) | c(FALSE, FALSE, FALSE)

# Result: TRUE, FALSE, TRUE

- **Cause**: Each element of the vectors is compared individually.

4. **Logical OR (`||`)**: Evaluates only the first element of each vector and returns `TRUE`
if either is `TRUE`.

- **Example**:
c(FALSE, TRUE, FALSE) || c(TRUE, FALSE, TRUE)

# Result: TRUE

- **Cause**: `||` only considers the first elements, making it useful in conditional
statements where full vector evaluation isn’t needed.

5. **Logical NOT (`!`)**: Returns `TRUE` if the associated statement is `FALSE`,


effectively inverting the logical value.

- **Example**:

!TRUE # Result: FALSE

!c(TRUE, FALSE, TRUE)

# Result: FALSE, TRUE, FALSE

] - **Cause**: T90\he `!` operator inverts each logical value in a vector or a single logical
value.8888p[ty-8

### Summary

- **`&` and `|`**: Compare element-wise across entire vectors.

- **`&&` and `||`**: Only evaluate the first element, often used in control structures for
performance.

- **`!`**: Inverts the logical value, turning `TRUE` into `FALSE` and vice versa.

These logical operators are essential for decision-making and conditional logic in R, and
understanding their behavior can help you write efficient and correct code.

> c(TRUE, FALSE, TRUE) & c(TRUE, TRUE, FALSE)

[1] TRUE FALSE FALSE

> c(TRUE, FALSE, TRUE) && c(TRUE, TRUE, FALSE)

[1] TRUE

> c(TRUE, FALSE, TRUE) && c(FALSE, TRUE, FALSE)

[1] FALSE

> c(TRUE, TRUE, TRUE) && c(TRUE, TRUE, FALSE)


[1] TRUE

> c(FALSE, FALSE, TRUE) && c(FALSE, TRUE, FALSE)

[1] FALSE

> c(TRUE, FALSE, TRUE) | c(FALSE, TRUE, FALSE)

[1] TRUE TRUE TRUE

> c(TRUE, FALSE, TRUE) | c(FALSE, FALSE, FALSE)

[1] TRUE FALSE TRUE

> c(TRUE, FALSE, TRUE) | c(FALSE, TRUE, FALSE)

[1] TRUE TRUE TRUE

> c(FALSE, FALSE, TRUE) | c(FALSE, TRUE, FALSE)

[1] FALSE TRUE TRUE

> c(FALSE, TRUE, FALSE) || c(TRUE, FALSE, TRUE)

[1] TRUE

> !TRUE # Result: FALSE

[1] FALSE

> !c(TRUE, FALSE, TRUE)

[1] FALSE TRUE FALSE

Miscellaneous operators

R uses the following miscellaneous operators:

 The : operator creates a sequence of numbers from the left argument to the right one.
 The %in% operator returns TRUE if the left argument is in the vector to the right.
 The %*% operator performs matrix multiplication on two matrices.

### `:` Operator in R


The `:` operator is used to create a sequence of numbers, starting from the left argument and
ending with the right argument, incremented by 1.

**Example**:

1:5

# Result: 1, 2, 3, 4, 5

**Explanation**:

- In the example `1:5`, the `:` operator generates a sequence starting from `1` and ending at
`5`, with each number increasing by 1.

- This operator is useful for quickly creating a sequence of integers for tasks like iterating
over a range or indexing elements in a vector.

### `%in%` Operator in R

The `%in%` operator is used to check if elements of the left argument are present in the
vector specified on the right. It returns `TRUE` for each element that is found in the right-
hand side vector and `FALSE` otherwise.

**Example**:

```r

x <- c(1, 2, 3, 4, 5)

y <- c(2, 4, 6)

x %in% y

# Result: FALSE, TRUE, FALSE, TRUE, FALSE

**Cause**:

- The `%in%` operator compares each element of `x` to see if it exists in `y`.

- In this example:

- `1` is not in `y` (`FALSE`)

- `2` is in `y` (`TRUE`)

- `3` is not in `y` (`FALSE`)


- `4` is in `y` (`TRUE`)

- `5` is not in `y` (`FALSE`)

**Explanation**:

- `%in%` is particularly useful for filtering or subsetting data based on membership in a


vector. The operator efficiently checks each element in the left-hand vector against all
elements in the right-hand vector and provides a logical vector indicating the result.

Assignment Operators

Assignment Operators in R are used to assigning values to various data objects in R. The
objects may be integers, vectors, or functions. These values are then stored by the assigned
variable names. There are two kinds of assignment operators: Left and Right

Left Assignment (<- or <<- or =)

Assigns a value to a vector.

vec1 = c("ab", TRUE)


print (vec1)
Output : "ab" "TRUE"

Right Assignment (-> or ->>)

Assigns value to a vector.

c("ab", TRUE) ->> vec1


print (vec1)
Output : "ab" "TRUE"

The following R code illustrates the usage of all Relational Operators in R:

# R program to illustrate
# the use of Assignment operators
vec1 <- c(2:5)
c(2:5) ->> vec2
vec3 <<- c(2:5)
vec4 = c(2:5)
c(2:5) -> vec5

# Performing operations on Operands


cat ("vector 1 :", vec1, "\n")
cat("vector 2 :", vec2, "\n")
cat ("vector 3 :", vec3, "\n")
cat("vector 4 :", vec4, "\n")
cat("vector 5 :", vec5)

Output

vector 1 : 2 3 4 5
vector 2 : 2 3 4 5
vector 3 : 2 3 4 5
vector 4 : 2 3 4 5
vector 5 : 2 3 4 5

Arithmetic Operators

Arithmetic Operators modulo using the specified operator between operands, which may be
either scalar values, complex numbers, or vectors. The R operators are performed element-
wise at the corresponding positions of the vectors.

Addition operator (+)

The values at the corresponding positions of both operands are added. Consider the following
R operator snippet to add two vectors:

a <- c (1, 0.1)


b <- c (2.33, 4)
print (a+b)
Output : 3.33 4.10

Subtraction Operator (-)

The second operand values are subtracted from the first. Consider the following R operator
snippet to subtract two variables:

a <- 6
b <- 8.4
print (a-b)
Output : -2.4

Multiplication Operator (*)

The multiplication of corresponding elements of vectors and Integers are multiplied with the
use of the ‘*’ operator.

B= c(4,4)
C= c(5,5)
print (B*C)
Output : 20 20

Division Operator (/)

The first operand is divided by the second operand with the use of the ‘/’ operator.

a <- 10
b <- 5
print (a/b)
Output : 2

Power Operator (^)

The first operand is raised to the power of the second operand.

a <- 4
b <- 5
print(a^b)
Output : 1024

Modulo Operator (%%)

The remainder of the first operand divided by the second operand is returned.

list1<- c(2, 22)


list2<-c(2,4)
print(list1 %% list2)
Output : 0 2

The following R code illustrates the usage of all Arithmetic R operators.

# R program to illustrate
# the use of Arithmetic operators
vec1 <- c(0, 2)
vec2 <- c(2, 3)

# Performing operations on Operands


cat ("Addition of vectors :", vec1 + vec2, "\n")
cat ("Subtraction of vectors :", vec1 - vec2, "\n")
cat ("Multiplication of vectors :", vec1 * vec2, "\n")
cat ("Division of vectors :", vec1 / vec2, "\n")
cat ("Modulo of vectors :", vec1 %% vec2, "\n")
cat ("Power operator :", vec1 ^ vec2)

Output

Addition of vectors : 2 5
Subtraction of vectors : -2 -1
Multiplication of vectors : 0 6
Division of vectors : 0 0.6666667
Modulo of vectors : 0 2
Power operator : 0 8
Logical Operators

Logical Operators in R simulate element-wise decision operations, based on the specified


operator between the operands, which are then evaluated to either a True or False boolean
value. Any non-zero integer value is considered as a TRUE value, be it a complex or real
number.

Element-wise Logical AND operator (&)

Returns True if both the operands are True.

list1 <- c(TRUE, 0.1)


list2 <- c(0,4+3i)
print(list1 & list2)
Output : FALSE TRUE
Any non zero integer value is considered as a TRUE value, be it complex or
real number.

Element-wise Logical OR operator (|)

Returns True if either of the operands is True.

list1 <- c(TRUE, 0.1)


list2 <- c(0,4+3i)
print(list1|list2)
Output : TRUE TRUE

NOT operator (!)

A unary operator that negates the status of the elements of the operand.

list1 <- c(0,FALSE)


print(!list1)
Output : TRUE TRUE

Logical AND operator (&&)

Returns True if both the first elements of the operands are True.

list1 <- c(TRUE, 0.1)


list2 <- c(0,4+3i)
print(list1[1] && list2[1])
Output : FALSE
Compares just the first elements of both the lists.

Logical OR operator (||)

Returns True if either of the first elements of the operands is True.

list1 <- c(TRUE, 0.1)


list2 <- c(0,4+3i)
print(list1[1]||list2[1])
Output : TRUE
The following R code illustrates the usage of all Logical Operators in R:

# R program to illustrate
# the use of Logical operators
vec1 <- c(0,2)
vec2 <- c(TRUE,FALSE)

# Performing operations on Operands


cat ("Element wise AND :", vec1 & vec2, "\n")
cat ("Element wise OR :", vec1 | vec2, "\n")
cat ("Logical AND :", vec1[1] && vec2[1], "\n")
cat ("Logical OR :", vec1[1] || vec2[1], "\n")
cat ("Negation :", !vec1)

Output

Element wise AND : FALSE FALSE


Element wise OR : TRUE TRUE
Logical AND : FALSE
Logical OR : TRUE
Negation : TRUE FALSE
Relational Operators

The Relational Operators in R carry out comparison operations between the corresponding
elements of the operands. Returns a boolean TRUE value if the first operand satisfies the
relation compared to the second. A TRUE value is always considered to be greater than the
FALSE.

Less than (<)

Returns TRUE if the corresponding element of the first operand is less than that of the second
operand. Else returns FALSE.

list1 <- c(TRUE, 0.1,"apple")


list2 <- c(0,0.1,"bat")
print(list1<list2)
Output : FALSE FALSE TRUE

Less than equal to (<=)

Returns TRUE if the corresponding element of the first operand is less than or equal to that of
the second operand. Else returns FALSE.

list1 <- c(TRUE, 0.1, "apple")


list2 <- c(TRUE, 0.1, "bat")

# Convert lists to character strings


list1_char <- [Link](list1)
list2_char <- [Link](list2)

# Compare character strings


print(list1_char <= list2_char)
Output : TRUE TRUE TRUE

Greater than (>)


Returns TRUE if the corresponding element of the first operand is greater than that of the
second operand. Else returns FALSE.

list1 <- c(TRUE, 0.1, "apple")


list2 <- c(TRUE, 0.1, "bat")
print(list1_char > list2_char)
Output : FALSE FALSE FALSE

Greater than equal to (>=)

Returns TRUE if the corresponding element of the first operand is greater or equal to that of
the second operand. Else returns FALSE.

list1 <- c(TRUE, 0.1, "apple")


list2 <- c(TRUE, 0.1, "bat")
print(list1_char >= list2_char)
Output : TRUE TRUE FALSE

Not equal to (!=)

Returns TRUE if the corresponding element of the first operand is not equal to the second
operand. Else returns FALSE.

list1 <- c(TRUE, 0.1,'apple')


list2 <- c(0,0.1,"bat")
print(list1!=list2)
Output : TRUE FALSE TRUE

The following R code illustrates the usage of all Relational Operators in R:

# R program to illustrate
# the use of Relational operators
vec1 <- c(0, 2)
vec2 <- c(2, 3)

# Performing operations on Operands


cat ("Vector1 less than Vector2 :", vec1 < vec2, "\n")
cat ("Vector1 less than equal to Vector2 :", vec1 <= vec2, "\n")
cat ("Vector1 greater than Vector2 :", vec1 > vec2, "\n")
cat ("Vector1 greater than equal to Vector2 :", vec1 >= vec2, "\n")
cat ("Vector1 not equal to Vector2 :", vec1 != vec2, "\n")

Output

Vector1 less than Vector2 : TRUE TRUE


Vector1 less than equal to Vector2 : TRUE TRUE
Vector1 greater than Vector2 : FALSE FALSE
Vector1 greater than equal to Vector2 : FALSE FALSE
Vector1 not equal to Vector2 : TRUE TRUE
Miscellaneous Operators

Miscellaneous Operator are the mixed operators in R that simulate the printing of sequences
and assignment of vectors, either left or right-handed.

%in% Operator

Checks if an element belongs to a list and returns a boolean value TRUE if the value is
present else FALSE.

val <- 0.1


list1 <- c(TRUE, 0.1,"apple")
print (val %in% list1)
Output : TRUE
Checks for the value 0.1 in the specified list. It exists, therefore,
prints TRUE.

%*% Operator

This operator is used to multiply a matrix with its transpose. Transpose of the matrix is
obtained by interchanging the rows to columns and columns to rows. The number of columns
of the first matrix must be equal to the number of rows of the second matrix. Multiplication
of the matrix A with its transpose, B, produces a square matrix.

You might also like