R-programming
Topics
• Introduction to R
• Setting Up the environment
• Data types
• Arithmetic operator and operations
• Data structures in R: List, Matrices, Vector,
DataFrame,
• Data import and export
• Statistical analysis with ggplot
R- installation
• Install R (the programming language)
• Go to CRAN: Open your web browser and navigate to
[Link].
• Select OS: Click the link for your operating system
(Windows, macOS, or Linux).
• Download Base R:
– Windows: Click "Download R for Windows," then "install R for
the first time," and then "Download R".
• macOS: Select the version for Apple silicon (M1/M2) or
Intel.
• Run the Installer: Open the downloaded file
(e.g., R-(version).exe) and follow the prompts, generally
accepting the default settings.
Introduction to R
• R is an open-source programming language
and software environment designed
specifically for statistical computing, data
analysis, and visualization.
• Developed in the early 1990s, it has become a
powerful, widely used tool for data scientists,
statisticians, and researchers across various
industries.
Variable
• variables are containers for storing data and
are created when a value is assigned to them,
without needing explicit declaration of data
types.
• R is a dynamically typed language, meaning
the data type of a variable can change
depending on the value assigned to it.
• Creating Variables
• Values can be assigned to variables using the leftward (<-),
rightward (->), or equal (=) operators.
• The leftward assignment operator (<-) is generally
preferred in R programming.
• # Assigning a value using the preferred leftward operator
• Ex: my_variable <- 10
• Ex: name = “Rohan” # Using the equal operator is also valid
• Ex: "value" -> another_variable # Rightward operator
• Naming Rules :
• Valid variable names in R must follow specific conventions:
• 1. Can include letters, numbers, dots (.),
and underscores (_).
• 2. Must start with a letter or a dot (.).
• 3. If starting with a dot, the character immediately following
the dot cannot be a number.
• 4. Cannot start with a number or an underscore (_).
• 5. Are case-sensitive (e.g., age and Age are treated as
different variables).
• 6. Cannot be reserved keywords
(e.g., TRUE, FALSE, NULL, if, else).
Data Types
• A variable's data type (class) is determined by the
value it holds. You can check the class of a variable
using the class() function. Common data types
include:
• numeric: Stores decimal (floating-point) numbers. This
is the default for most numbers.
• integer: Stores whole numbers. An L suffix is used to
explicitly define an integer (e.g., 10L).
• logical: Stores boolean values (TRUE or FALSE).
• character: Stores single characters or strings of text
(e.g., "hello").
• complex: Stores numbers with an imaginary
component (e.g., 1 + 4i).
• Ex: a=5
• B=3.4
• C=True
• D=3+4i
• E=“Hello”
Operators
• 1. Addition operator (+)
• Ex: a=3, b=4
• > print(a+b)
• 2. Subtraction Operator (-)
• Ex: a=7, b=4
• > print(a-b)
• 3. Multiplication Operator (*)
• Ex: a=7, b=4
• > print(a*b)
• 4. Division Operator (/)
• 5. Power Operator (^)
• 6. Modulo Operator (%%)
Data structures in R
• R has several built-in data structures
• 1. Vector
• 2. List
• 3. Matrices
• 4. Dataframe,
•1. Vectors: One-dimensional, homogeneous
structures.
• The c() function in R is useful for creating (small)
vectors and for modifying existing vectors. Think
of c as standing for “combine”.
• Ex:
weight <- c(123, 157, 205, 199, 223, 140, 105)
print(weight)
123, 157, 205, 199, 223, 140, 105 #output
• typeof(weight) or class(weight)
• Double #output
• Accessing Specific Elements of Vectors
• To access and possibly change specific
elements of vectors, refer to the position of
the element in square brackets.
• For example, weight[4]
• 199 #output
Vectors
– Create a vector
v1 <- c(1,2,3,4,5)
x <- vector(“numeric”, length= 10) The R code x <-
vector("numeric", length = 10) creates an empty
numeric vector named x that is capable of holding 10
elements. All elements are initialized to the value 0
(zero).
[1] 0 0 0 0 0 0 0 0 0 0
y <- seq(10,20)
The variable y will contain the following elements:
[1] 10 11 12 13 14 15 16 17 18 19 20
Vectors
– y <- seq(10,20,5)
The resulting vector y contains the values: 10, 15, 20.
– num <- 1:10
– num <- c(1:10, 10.5)
The variable num is a numeric vector of length 11
containing the values (1,2,3,4,5,6,7,8,9,10,10.5).
– ltrs <- letters[1:10]
If you print ltrs in R, it will display:
[1] "a" "b" "c" "d" "e" "f" "g" "h" "i" "j"
– mixed_vec <- c(num,ltrs)
mixed_vec <- c(num,ltrs)
> mixed_vec
[1] "1" "2" "3" "4" "5" "6" "7" "8" "9" "10"
"10.5" "a"
[13] "b" "c" "d" "e" "f" "g" "h" "i" "j"
Access Elements
• v1 <- c(10, 20, 30, 40, 50, 60, 70, 80)
• v1[4]: Gets the 4th element (which is 40).
• v1[-3]: Gets all elements except the 3rd from the end (so,
everything but 60).
• v1[-1]: Gets all elements except the last one (so, everything
but 80).
• v1[2:5]: Gets elements from the 2nd to the 5th position (i.e.,
20, 30, 40, 50).
Access Elements
• # Sample Vectors
• y <- c(10, 20, 30, 40, 50, 60, 70) # Example
vector 'y'
• ltrs <- letters # 'letters' is a built-in R vector:
c("a", "b", "c", ...)
• y[3]: Selects the 3rd element from vector y.
• 30 (from y).
• y[-1]: Selects all elements of y except the last one.
• c(10, 20, 30, 40, 50, 60).
• y[-3]: Selects all elements of y except the 3rd one.
• c(10, 20, 40, 50, 60, 70)
Access Elements
• # Sample Vectors
• y <- c(10, 20, 30, 40, 50, 60, 70) # Example vector
'y'
• ltrs <- letters # 'letters' is a built-in R vector: c("a",
"b", "c", ...)
• y[2:6]
• Selects a range of elements from the 2nd to the 6th.
• c(20, 30, 40, 50, 60)
• ltrs[c(2,5,8,10)]
• Selects specific, non-consecutive elements (2nd, 5th, 8th, 10th)
from ltrs.
• c("b", "e", "h", "j")
• Concatenate vectors
a <- c(10,20,30)
b <- c(40,50,60)
res <- c(a,b)
Res
a <- c(10,20,30): Creates a numeric vector a with
elements 10, 20, 30.
b <- c(40,50,60): Creates a numeric vector b with
elements 40, 50, 60.
res <- c(a,b): Concatenates vectors a and b into a
new vector, res, resulting in 10, 20, 30, 40, 50, 60.
res: Prints the resulting vector.
• Arithmetic operations on a vectors
a+b
a-b
a*b
a/b
a%%b
b%%a
The syntax a %% b in R uses the modulo operator, which returns the
remainder of the division of a by b. The expression b %% a returns the
remainder of the division of b by a.
Examples in R
.
a %% b (a modulo b): Returns the remainder when a is divided by b.
R
a <- 5
b <- 2
print(a %% b)
# Output: [1] 1
b %% a (b modulo a): Returns the remainder when b is divided by a.
R
a <- 5
b <- 2
print(b %% a)
# Output: [1] 0
%/%: Integer division, which returns the
quotient as an integer, discarding any
fractional part.
R
a <- 5
b <- 2
print(a %/% b)
# Output: [1] 2
%*%: Matrix multiplication.
%in%: Matching operator, used to check if
elements of a vector are present in another
vector.
• Deleting the vector
a=NULL
[Link](a) # Returns TRUE
[Link](NA) # Returns FALSE
• Sorting a vector
a=c(60,90,30,20,40,70)
sort(a)
sort(a, decreasing=TRUE)
Modify the elements of a vector
a[2] =0
a[a>10]
To modify elements of a vector in R, you use
subsetting combined with the assignment
operator <-.
Step 1: Assign a value to a specific index To
change a specific element, provide its position
in square brackets.
The command a[2] = 0 (or more idiomatic a[2]
<- 0) replaces the second element of the vector
with 0.
Modify the elements of a vector
To modify multiple elements that meet a specific criterion,
such as being greater than 10, use logical indexing. The
expression a > 10 creates a boolean mask, and passing
this into the brackets allows you to target only those
values for reassignment.
a[2] <- 0
a[a > 10] <- 10
The first line replaces the value at index 2 with 0. The
second line identifies all values in a where the condition
(a>10) is true and assigns them the value 10.
• 2. List:
• List is an ordered collection of objects. Lists are
heterogeneous data structures. These are also
one-dimensional data structures. A list can be a list of
vectors, list of matrices, a list of characters and a list of
functions and so on.
• Ex:
• > empId = c(1, 2, 3, 4)
• > empName = c("Debi", "Sandeep", "Subham", "Shiba")
• >numberOfEmp = 4
• > empList = list(empId, empName, numberOfEmp)
• > print(empList)
List
• Create a list
test <- list()
• Add elements to a list
test <- list(“music tracks”, 100,5.0, TRUE, 3+i4)
• Access elements of a list
test[2]
test[1:3]
test[c(1,2,3)]
test[c(1,3,5)]
• Nested list
test <- list(list(10,2.5,”IBS”), “R Programming”, 50.5)
test[[1]][[2]]
test[2]
test <- list(list(“Abhilash”, “Suraj”),
list(101,102),list(93.4,98.6))
names(test) <- c(“name_of_student”, “roll_no”,
“percentage”)
test[“roll_no”]
test <- c(“music tracks”, 100,5)
test
class(test)
test <- list(“music tracks”, 100,5)
test
[Link](test)
test <- list(“music tracks”, 100,5)
names(test) <- c(“product”, “count”, “rating”)
test
test[[1]]
test[[2]]
test[[3]]
[Link] <- list(product = “music tracks”,
count=100, ratings=5)
[Link]
str([Link])