R-PROGRAMMING PROF.
AJAY K V
R-PROGRAMMING UNIT 1
1. What is R-Programming?
● R is a programming language and software environment for statistical analysis, graphics
representation, and reporting.
● R is freely available under the GNU General Public License, and pre-complied binary
versions are provided for various operating systems like Linux, Windows, and Mac.
● R was created by Ross Ihaka and Robert Gentleman at the University of Auckland, New
Zealand, and is currently managed by the R Development Core Team.
2. What are the Applications of R-programming.
● R is very widely used for data science.
● R also helps in importing and cleaning data and quantitative analysis.
● R has applications in a wide range of industries such as academics, healthcare, government,
insurance, energy, retail, media, manufacturing, technology, and electronics.
● Statistical computing(9100+packages).
● Machine Learning (ML tasks like linear and non-linear regression, decision trees, linear and
non-linear classification and many more).
3. Explain the advantages and disadvantages of R-programming.
Advantages:
This is a rapidly developing language with many advantages.
Some significant advantages of R programming include its versatility, open-source nature,
diverse extensions, quality data visualization, etc.
1. Open-Source Language: R is an open-source language accessible to anyone. Users do not
need any paid licensing or permissions to access it. One can easily contribute and modify the
source code.
2. Platform independent: The R Language is platform-independent, meaning it can run on
various operating systems, including Windows, mac OS, and Linux, providing flexibility in
development environments.
3. Machine Learning Operations: R allows us to do various machine learning operating
operations such as classification and regresssion. For this purpose, R provides various packages
and features for developing the artificial neural network. R is used by the best data scientists in
the world.
4. Exemplary support for data wrangling: R allows us to perform data wrangling. R provides
packges such as dplyr, readr which are capable of transforming messy data into a structured
form.
5. Quality plotting and graphing: R simplifies quality plotting and graphing, R libraries such
as gglpot2 and plotly advocates for visually appealing and aesthetic graphs which set R apart
from other programming languages.
6. The array of packages: R has a rich set of packages. R has over 10,000 packages in the
CRAN repository which are constantly growing. R provides packages for data science and
machine learning operations.
1
R-PROGRAMMING PROF. AJAY K V
7. 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.
8. 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.
9. Statistics: R is mainly know as the language of statistics. It is the main reason why R is
predominant than other programming languages for the development of statistical tools.
Disadvantages:
1. Steep Learning Curve: R’s unique syntax, functional style, and data structures (vectors, lists,
data frames) can overwhelm beginners without statistical or programming backgrounds,
making it harder to learn compared to languages like Python.
2. Memory Inefficiency: R holds all objects in RAM. This makes handling large datasets prone
to performance slowdowns or crashes unless you adopt specialized packages or external tools.
3. Slower Execution Speed: As an interpreted language, R executes code more slowly than
compiled languages like C, C++ or Python—especially during complex computations or real-
time data processing.
4. Limited General-Purpose Use: R is optimized for statistical analysis; it lacks comprehensive
features for general-purpose or software development tasks—like web, mobile, GUI apps—
where languages like Python or Java excel
5. Single-Threaded Limitation: By default, R runs single-threaded. While parallel or multi-
threaded execution is possible with additional packages, it adds complexity and often requires
significant code changes.
4. What are keywords, variables, comments in R-programming.
● Keywords are specific reserved words in R, each of which has a specific feature associated
with it.
Almost all of the words which help one to use the functionality of the R language are included
in the list of keywords.
Ex: If, Else, repeat, while, Function, for, next, Break… ...,
● Variable: Variables are the memory location to store the values. Ex: X=10, Y<-20, 30->A.
● Comments: Comments are the programmer readable explanation in the source code of an R
program.
The purpose of adding these comments is to make the source code easier to understand.
These comments are generally ignored by compilers and interpreters.
1. Single-Line Comments:
The # symbol to start a single-line comment. Anything after # on the same line is considered
a comment and will not be executed.
Example:
# This is a comment
“Hello World!”
2. Multi-Line Comments:
2
R-PROGRAMMING PROF. AJAY K V
R does not have a built-in syntax for multi-line comments, but you can use triple backticks
(“’) or triple quotes (“””) to create multi-line character strings, which can serve as
comments.
Example:
“’
This is a multi-line comment.
It spans across multiple lines.
“’
3
R-PROGRAMMING PROF. AJAY K V
5. Explain the different data types in R-programming.
1. Numeric: Numeric data types are used to store real or integer numbers.
Example:
x<-5 #Numeric integer
y<-3.14 #Numeric real
2. Character: Character data types are used to store text and are enclosed in quotes (single or
double). R supports character data types where you have all the alphabets and special characters. It
stores character values or strings. Strings in R can contain alphabets, numbers, and symbols.
Examples:
Name<-”Alice”
City<-’New York’
3. Integer: Set of all integers, Z R supports integer data types which are the set of all integers.
You can create as well as convert a value into an integer type using the [Link]()
function.
You can also use the capital ‘L’ notation as a suffix to denote that a particular value is
of the integer R data type.
Example: "integer_value <- 42L“
4. Logical: Logical data types represent Boolean values, which can be either TRUE or FALSE.
Example:
is_student<-TURE
has_car<-FALSE
5. Complex: Complex data types are used to represent complex numbers. They have both real
and imaginary parts.
Example: z<-3+2!
6. raw:[Link]() To save and work with data at the byte level in R, use the raw data type. By
displaying a series of unprocessed bytes, it enables low-level operations on binary data.
Example:"single_raw <- [Link](255)“
6. Explain the operators in R-programming.
● Operators are symbols or special functions used to perform various operations on data.
● R supports a wide range of operators for arithmetic, logical, relational, and assignment
operator, Miscellaneous operators.
a. Arithmetic Operators: Arithmetic operators are used with numeric values to perform
common mathematical operations.
Examples: + , -, *, /, ^
b. Assignment Operators: An assignment is used to assign a new value to a variable. In
R, these operators are used to assign values to vectors.
Examples: =, <-, ->
c. Comparison Operators/Relational Operators: These operators are used to
compare values and return logical result (TURE or FALSE).
Examples: ==, !=, >, <, <=, >=
4
R-PROGRAMMING PROF. AJAY K V
d. Logical Operators: The logical operators allow a program to make a decision on the
basic of multiple conditions.
Examples: &, |, &&, ||
e. Miscellaneous Operators: Miscellaneous operators are used to manipulate data. And
specific task.
Examples: :, %in%, %*%
Overall example for operators in R -Programming:
#Arithmetic Operators
a<-c(10,20,30)
b<-c(40,50,60)
print(a+b)
print(a-b)
print(a*b)
print(a/b)
print(a%%b)
print(a%/%b)
#Assignment Operators
x=20
print(x)
y<-30
print(y)
40->z
print(z)
#Relational Operators
a=c(10,40,50)
b=c(30,20,10)
print(a==b)
print(a!=b)
print(a>b)
print(a>b)
print(a>=b)
print(a<=b)
#Logical Operators
a=20
b=30
m=20
n=30
print(a&b)
print(a|b)
print(!a)
print(!b)
print((a>b)&&(m>n))
print((a>b)||(m>n))
#Miscellaneous Operators
a=1:10
print(a)
b=8
print(b%in%a)
x=c(10,20,30)
y=c(40,50,60)
print(x%*%y)
5
R-PROGRAMMING PROF. AJAY K V
7. Explain the Data Structures in R-programming.
A data structure is a particular way of organizing data in a computer so that it can be used
effectively. The idea is to reduce the space and time complexities of different tasks. Data
structures in R programming are tools for holding multiple values.
The most essential data structures used in R include: Vectors, Lists, Data frames,
Matrices, Arrays.
1. Vector: A vector is a fundamental data structure that allows you to store manipulate a
collection of elements. Vectors can be of different data types, such as numeric, character,
logical, or factor, The elements which are contained in vector known as components of vector.
● A vector length is basically the number of elements in the vector, and it is calculated
with the help of the length () function.
● There are various methods to create vector in R programming. The most common way
is to use the c() function , which stands for “combine” or concatenate”, To create a
vector with numerical values in a sequence, use the : operator.
Example:
Fruits<-c(“apple” “banana” “cherry”)
Fruits
output:[1]”apple” “banana” “cherry”.
Vectors Functions:
1. Vector Length: To find out how many items a vector has, use the length() function.
Example: fruits <- c("banana", "apple", "orange")
length(fruits)
Output: [1] 3
2. Sort a Vector: To sort items in a vector alphabetically or numerically, use the sort() function:
Example: fruits <- c("banana", "apple", "orange")
n <-c(5,6,1,8)
sort(fruits)
sort(n)
Output:[1] “apple” “banana” “orange”
[1] 1 5 6 8
3. Access Vectors: Access the vector items by referring to its index number inside brackets [].
The first item has index 1, the second item has index 2, and so on
Example: fruits <- c("banana", "apple", "orange")
fruits[c(1,2)]
6
R-PROGRAMMING PROF. AJAY K V
Output: [1] "banana" "apple"
4. Change an Item: To change the value of a specific item, refer to the index number.
Example: fruits <- c("banana", "apple", "orange")
fruits[2]<- "Mango"
fruits
Output:[1] “banana” “Mango” “orange”
5. Sequenced Vectors: To create a vector with numerical values in a sequence with the
operator.
Example: number<-1:10
numbers
Output: [1] 1 2 3 4 5 6 7 8 9 10
2. List: A list is like a vector. However, an element of a list can be an object object of any
type and structure.
● Consequently, a list can contain another list and therefore it can be used to construct
arbitrary data structures.
● A list can also be constructed by using the function list(). The names of the list
components and the contents of list components can be specified as arguments of the list
function by using the ‘=‘ character.
● List Functions:
R provides various functions for working with lists, includes:
● Length(): Returns the number of elements in a list.
● Names(): Retrieves or sets the names of the elements in a list.
● Str(): Displays the structure of a list, showing its elements and data types.
● Unlist(): Converts a list to a vector by flattening it.
● Lists Creation:
● The process of creating a list is the same as a vector. In R, the vector is created with the
help of c() function.
Like c() function, there is another function, i.e., list() which is used to create a list in R.
A list avoid the drawback of the vector which is data type.
Syntax: list()
Example:
lst <-list(“apple”, “banana”, “cherry”)
Lst
7
R-PROGRAMMING PROF. AJAY K V
Output:
[[1]]
[1]”apple”
[[2]]
[1]”banana”
[[3]]
[1]”cherry”
3. Matrix: In R, a two-dimensional rectangular data set is known as a matrix. A matrix is
created with the help of the vector input to the matrix function. On R matrices, we can perform
addition, subtraction, multiplication, and division operation.
Creating Matrix: Creating a matrix in R using the matrix () function.
Syntax of The Matrix in R
Matrix (data, nrow, ncol, byrow, dim_name)
Data: The first argument in the matrix function is data. It is the input vector which is the data
elements of the matrix.
Nrow: The second argument is the number of rows that we want to create in the matrix.
Ncol: The third argument is the number of columns that we want to create in the matrix.
Byrow: The byrow parameter is a logical clue. If its value is true, then the input vector elements
are arranged by row.
Dim_name: The dim_name parameter is the name assigned to the rows and columns
EX: m<-matrix (data=1:12, nrow=3, byrow=TRUE, ncol=5)
Print(m)
4. Data Frame: Data frame is two-dimensional array-like structure or a table in which a
column contains values of one variables, and rows contains one set of values from each column.
How to create Data Frame: The data frames are created with the help of frame() function of
data. This function contains the vectors of any type such as numeric, character, or integer.
While the first column can be character, the second and third can be numeric or logical.
However, each column should have the same type of data.
Example
#Create a data frame
8
R-PROGRAMMING PROF. AJAY K V
Dframe<- [Link] (Training- c("Strength", "Stamina", "Other"),
Pulsec(100, 150, 120), Duration c(60, 30, 45))
Print(Dframe)
5. Array: Arrays are generalizations of vectors and matrices. A vector is a one-dimensional
array and a matrix is a two-dimensional array. As with vectors and matrices, all the elements
of an array must be of the same data type. One can create an array easily with the array ()
function, where one give the data as the first argument and a vector with the sizes of the
dimensions as the second argument. The number of dimension sizes in that argument gives you
the number of dimensions.
Creating Arrays: To create an array in R it is quite simple. We can easily create an array using
vector and array() function. In array, data is stored in the form of the matrix the array() function.
This function takes the following arguments:
R Array Syntax
array_name <array (data, dim (row_size, column_size, matrices, dim_names))
Data: The data is the first argument in the array() function. It is an input vector which is given
to the array.
Dim: A vector specifying the dimensions of the array. For a 2D array, the c() function is to
specify the number of rows and columns. the dim parameter is to specify the dimensions
array_name <array(data, dim (row_size, column_size, matrices, dim_names))
matrices: In R, the array consists of multi-dimensional matrices.
row_size: This parameter defines the number of row elements which an array can store.
column_size: This parameter defines the number of columns elements which an array can store.
dim names: This parameter is used to change the default names of rows and columns.
An array with one dimension with values ranging from 1 to 24
A<- c(1:24)
A
Output: [1]
1234 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
An Array with more than One Dimension
ma - array(A, dim = c(4, 3, 2))
ma
9
R-PROGRAMMING PROF. AJAY K V
8. Explain different types of classes in R-programming.
Classes: Classes are used to define custom data types and structures for creating objects.
Classes are a fundamental part of object-oriented programming (OOP) in R and enable
you to organize data and functions in a structured and reusable way. There are three class
systems in R
● S3 Class
● S4 Class
● Reference Class in R
S3 Classes: Statistical Computing and R Programming S3 is a simple and informal system
for defining and working with classes.
$3 classes are characterized by the use of class attributes.
Classes are determined by the value of the class attribute associated with objects.
S3 classes are easy to create, and many base R functions and packages use S3 classes.
Create a list with various components then we create a class using the class() function
#create a list with required components
Student1<-list(name "John", age 21, GPA = 3.5)
#name the class appropriately
class(student1) "Student_Info"
#create and call an object
Student 1
Output:
Sname
[1] "John"
Sage
[1] 21
SGPA
[1] 3.5
attr(, "class")
[1] "Student Info"
Note: Student Info is the class name
S4 Classes: S4 is a more formal and robust system for defining and working with classes.
S4 classes are characterized by a well-defined, formal structure. Classes are typically used in
10
R-PROGRAMMING PROF. AJAY K V
more complex and specialized scenarios. S4 class use the setClass() function from the
methods package.
To create an object, we use the new() function
#create a class "Student_Info" with three member variables
setClass("Student_Info", slots-list(name="character", age="numeric", GPA="numeric"))
#create an object of class
student1 - new("Student_Info", name = "John", age=21, GPA 3.5)
#call student! object
student!
Output:
An object of class "Student Info"
Slot "name":
[1] "John"
Slot "age":
[1] 21
Slot "GPA
[1] 3.5
Reference Class in R: Reference class is similar to defining a S4 class. Instead of
setClass() we use the setRefClass() function.
#create a class "Student_ Info" with three member variables
Student Info setRefClass("Student Info".
fields list(name "character", age"numeric", GPA - "numeric"))
#Student_Info() is our generator function which can be used to create new objects
student! - Student Info(name "John", age 21, GPA-3.5)
#call student object
student!
Output:
Reference class object of class "Student_Info"
Field "name":
[1] "John"
11
R-PROGRAMMING PROF. AJAY K V
Field "age":
[1] 21
Field "GPA":
[1]3.5
9. What is Coercion? Explain its types?
Coercion is the process of automatically converting data from one data type to another, typically
to make operations and calculations between different data types work correctly. Coercion can
be either implicit (automatic) or explicit (user-defined).
Implicit Coercion: In many cases, R will implicitly perform coercion when necessary to make
expressions or operations work. For example, when you add an integer and a numeric value, R
will coerce the integer to a numeric type to match the data types.
Example:
X<-5
Y<-3.5
result<-x+y
Print(result)
Output: [1] 8.5
Explicit Coercion: You can explicitly coerce data types using functions like as numeric() as
integer), as character(), etc. This allows you to convert data from one type to another based on
your requirements.
Example:
x5
[Link](x)
print(y)
Output: [1] 5
12
R-PROGRAMMING PROF. AJAY K V
10. Explain the Special Values in R programming.
In R, there are several special values or reserved values that have specific meanings and
uses in programming and data analysis. Some of the most common special values in R
include:
● NA (Not Available): NA represents missing or undefined values. It is used to indicate the
absence of a value. It is often used in data analysis to handle missing data points.
Example: v<-c(1,2,3)
Print(v)
Length(v)<-4
Print(v)
Output: [1] 1 2 3
[1] 1 2 3 NA
● NaN (Not a Number): NaN represents an undefined or unrepresentable value in
numerical calculations. It is often used when a mathematical operation doesn't result in a
valid numeric value.
0/0
output: [1] NaN
● Inf and -Inf (Positive and Negative Infinity): Inf represents positive infinity, and Inf
represents negative infinity. These values are used in cases where numeric calculations
lead to extreme values that are beyond the representable range.
2^1024 Output [1] Inf
-2^1024 Output [1]-Inf
● NULL: NULL is used to represent the absence of an object. It is different from NA and
indicates that no object is present. It is often used in functions that need to return nothing.
x< NULL
● NA_character: A specific type of NA for character vectors. It is used to represent
missing or undefined character data
my_vector <- c("A", "B", NA_character, "D")
Output: [1] "A" "B" NA "D"
13
R-PROGRAMMING PROF. AJAY K V
UNIT 1 QUESTION BANK
1. What is R-programming? Explain its Advantages and Disadvantages.
2. Explain data types in R-programming, Explain with an example.
3. Define keywords, and comments in R programming.
3. Explain operators in R-programming, Explain with an example.
4. What is Data Structures? Explain various Data Types in R-programming.
5. Define class? Explain Types of class with example.
6. Explain Special Values and Coercion with Example.
NOTE:
● Students these are important questions for unit-1.
● For data types write definition, syntax and examples.
● For data structures write definition, syntax and examples and write any two
functions for data structures don’t write all the functions.
● Refer this question bank for your exam.
14