Week 1-R Programming Notes
Week 1-R Programming Notes
It is recommended to visit the following website to have hands-on practice while studying these
lecture notes.
https://www.mycompiler.io/online-r-compiler
(This is the link for R Program Coding).
You will see the following interface after clicking on the above link.
Module 1
Week 1
1.1 What is the R console?
It is the place where commands written in the R language can be typed and executed.
1.2 R for Basic Math:
All common arithmetic operations and mathematical functionality are ready to use at the console
prompt. You can perform addition, subtraction, multiplication, and division with the symbols +, -,
*, and /, respectively. You can create exponents (also referred to as powers or indices) using ^,
and you control the order of the calculations in a single command using parentheses, ().
R> 2+3
[1] 5
R> 14/6
[1] 2.333333
R> 14/6+5
[1] 7.333333
R> 14/(6+5)
[1] 1.272727
Note: Here ‘R>’ is called R prompt. [1] indicates that it is the first among many outputs.
1.2.2 Exponent:
R> 3^2
[1] 9
R> 2^3
[1] 8
You can find the square root of any non-negative number with the sqrt function. You simply
provide the desired number to x as shown below:
R> sqrt(x=9)
[1] 3
R> sqrt(x=5.311)
[1] 2.304561
1.2.4 Exercise:
When using R, you’ll often find that you need to translate a complicated arithmetic formula into
code for evaluation (for example, when replicating a calculation from a textbook or research
paper). The next examples provide a mathematically expressed calculation, followed by its
execution in R
2 3×60
1. 10 + 8
− 3 Ans- 119.5
3
5 ×(6−2)
2. 61−3+4
Ans- 8.064516
2.25−0.25
2+1 2
3. 2 − 4 + 64 Ans- 16777220
0.44×(1−0.44) 0.5
4. ( 34
) Ans- 0.08512966
R> x <- 5
R> x
[1] 5
R> x = x + 1 # this overwrites the previous value of x by 1
R> x
[1] 6
R> mynumber = 45.2
R> y <- mynumber*x
R> y
[1] 271.2
R> ls()
[1] "mynumber" "x" "y"
As you can see from these examples, R will display the value assigned to an object when you
type the name of the object into the console. When you use the object in subsequent operations, R
will substitute the value you assigned to it. Finally, if you use the ls command to examine the
contents of the current workspace, it will reveal the names of the objects in alphabetical order
(along with any other previously created items). Although = and <- do the same thing, it is wise
(for the neatness of code if nothing else) to be consistent. Many users choose to stick with the <-,
however, because of the potential for confusion in using the = (for example, we clearly didn’t
mean that x is mathematically equal to x + 1 earlier). In these notes, we will do the same and
reserve = for setting function arguments, which begins. So far you’ve used only numeric values,
but note that the procedure for assignment is universal for all types and classes of objects, which
you’ll examine in the coming chapters. Objects can be named almost anything as long as the
name begins with a letter (in other words, not a number), avoids symbols (though underscores
and periods are fine), and avoids the handful of “reserved” words such as those used for defining
special values or for controlling code flow.
1.4 Vectors:
Often you’ll want to perform the same calculations or comparisons upon multiple entities, for
example if you’re rescaling measurements in a data set. You could do this type of operation one
entry at a time, though this is clearly not ideal, especially if you have a large number of items. R
provides a far more efficient solution to this problem with vectors. For the moment, to keep things
simple, you’ll continue to work with numeric entries only, though many of the utility functions
discussed here may also be applied to structures containing non-numeric values.
Note: Vector entries can be calculations or previously stored items (including vectors
themselves).
This code created a new vector assigned to the object myvec2. Some of the entries are defined as
arithmetic expressions, and it’s the result of the expression that’s stored in the vector. The last
element, my, is an existing numeric object defined as 32.1. Let’s look at another example.
This code creates and stores yet another vector, myvec3, which contains the entries of myvec and
myvec2 appended together in that order.
Note: The [1] shown in the output indicates that output is a vector and 1.000000 is its first
element and [7] indicates that 2.000000 is 7th element.
1.5 Sequences, Sorting, and Lengths:
Let’s create an equally spaced sequence of increasing or decreasing numeric values. This is
something you’ll need often, for example when programming loops or when plotting data points.
The easiest way to create such a sequence, with numeric values separated by intervals of 1, is to
use the colon operator.
R> 3:27
[1] 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
The example 3:27 should be read as “from 3 to 27 (by 1).” The result is a numeric vector just as if
you had listed each number manually in parentheses with c. As always, you can also provide
either a previously stored value or a (strictly parenthesized) calculation when using the colon
operator:
Note: The name foo and bar is not a real name: it is a placeholder, used to represent the name
of any desired thing.
R> seq(from=3,to=27,by=3)
[1] 3 6 9 12 15 18 21 24 27
By setting length.out to 40, you make the program print exactly 40 evenly spaced numbers from
3 to 27.
R> sort(x=c(2.5,-1,-10,3.44),decreasing=FALSE)
[1] -10.00 -1.00 2.50 3.44
R> sort(x=c(2.5,-1,-10,3.44),decreasing=TRUE)
[1] 3.44 2.50 -1.00 -10.00
R> foo <- seq(from=4.3,to=5.5,length.out=8)
R> foo
[1] 4.300000 4.471429 4.642857 4.814286 4.985714 5.157143 5.328571 5.500000
R> bar <- sort(x=foo,decreasing=TRUE)
R> bar
[1] 5.500000 5.328571 5.157143 4.985714 4.814286 4.642857 4.471429 4.300000
R> sort(x=c(foo,bar),decreasing=FALSE)
[1] 4.300000 4.300000 4.471429 4.471429 4.642857 4.642857 4.814286 4.814286
[9] 4.985714 4.985714 5.157143 5.157143 5.328571 5.328571 5.500000 5.500000
The sort function is pretty straightforward. You supply a vector to the function as the argument x,
and a second argument, decreasing, indicates the order in which you want to sort. This argument
takes a type of value you have not yet met: one of the all-important logical values. A logical
value can be only one of two specific, case-sensitive values: TRUE or FALSE. Generally
speaking, logicals are used to indicate the satisfaction or failure of a certain condition, and they
form an integral part of all programming languages. You’ll investigate logical values in R in
greater detail. For now, in regards to sort, you set decreasing=FALSE to sort from smallest to
largest, and decreasing=TRUE sorts from largest to smallest.
1.5.4 Vector Length with length:
The length function, which determines how many entries exist in a vector given as the argument
x.
R> length(x=c(3,2,8,1))
[1] 4
R> length(x=5:13)
[1] 9
R> foo <- 4
R> bar <- c(3,8.3,rep(x=32,times=foo),seq(from=-2,to=1,length.out=foo+1))
R> length(x=bar)
[1] 11
Note: The entries of the matrix are provided as a vector to the data argument, and you must make
sure that the length of this vector matches exactly with the number of desired rows (nrow) and
columns (ncol). You can elect not to supply nrow and ncol when calling matrix, in which case R’s
default behavior is to return a single-column matrix of the entries in data. For example,
matrix(data=c(-3,2,893,0.17)) is identical to matrix(data=c(-3,2,893,0.17),nrow=4,ncol=1).
R>rbind(x, y)
[,1] [,2] [,3]
x123
y 10 11 12
In R, the transpose of a matrix is found with the function t.In R, the transpose of a matrix is
found with the function t.
You can create an identity matrix of any dimension using the standard matrix function, but there
is a quicker approach using diag.
Here you see diag can be used to easily produce an identity matrix. To clarify, the behavior of
diag depends on what you supply to it as its argument x. If, as earlier, x is a matrix, diag will
retrieve the diagonal elements of the matrix. If x is a single positive integer, as is the case here,
then diag will produce the identity matrix of the corresponding dimension.
The notion of every element in a matrix being multiplied by some constant amount fits right into
R’s element-wise behavior. Scalar multiplication of a matrix is carried out using the standard
arithmetic * operator.
R> A <- rbind(c(2,5,2),c(6,1,4))
R> a <- -2.5
R> a*A
[,1] [,2] [,3]
[1,] -5 -12.5 -5
[2,] -15 -2.5 -10
1.6.6 Matrix Addition and Subtraction:
For any two matrices A and B of equal size, addition or subtraction is performed in an
element-wise fashion, where corresponding elements are added or subtracted from one another,
depending on the operation. Here’s an example:
Again, the standard operational mode of R is to proceed in an elementwise fashion, which means
you can add or subtract any two equally sized matrices with the standard + and - symbols.
This confirms the two matrices are compatible to be multiplied by one another, so you can
proceed.
R> A%*%B
[,1] [,2]
[1,] 3 9
[2,] 21 3
You can show that matrix multiplication is noncommutative using the same two matrices.
Switching the order of multiplication gives you an entirely different result.
R> B%*%A
[,1] [,2] [,3]
[1,] -12 12 -6
[2,] 4 -4 2
[3,] 32 10 22
1.6.8 Matrix Inversion:
You can also verify that the product of these two matrices (using matrix multiplication rules)
results in the 2 × 2 identity matrix.
R> A%*%solve(A)
[,1] [,2]
[1,] 1 0
[2,] 0 1
Exercise
1.1 Vimal Industries has issued 60,000 shares of par value Rs. 10 each. The company
declared a total dividend of Rs. 72,000. Find the rate of dividend paid by the company.
Calculate using R Programming.
1.2 Create a vector with following numbers 3, 67.0.98,123,67.89,-0.34 and store it as a new
object in R. Sort this vector in ascending order and measure its length. Also create a
sequence of exactly 42 evenly spaced numbers from 5 to 30.
1.3
𝑇
Calculate A𝐵
*****