R Lab
R Lab
Develop a program to create two 3 X 3 matrices A and B and perform the following operations a)
Transpose of the matrix b) addition c) subtraction d) multiplication
Output:
#A #B
[, 1] [, 2] [, 1] [, 2]
[1, ] 10 8 [1, ] 5 3
[2, ] 5 12 [2, ] 15 6
These matrices are both of the same dimensions. You can check the dimensions (number of rows and
columns, respectively) of a matrix with the dim function.
dim(A) # 2 2
dim(B) # 2 2
> t(A)
[,1] [,2]
[1,] 10 5
[2,] 8 12
> t(B)
[,1] [,2]
[1,] 5 15
[2,] 3 6
b) addition:
Addition of A & B:
A+B
> A+B
[,1] [,2]
[1,] 15 11
[2,] 20 18
KIT/CSE/ BDS306C/M5/BJ DATA ANALYTICS WITH R Page 41
Subtraction of B from A:
A-B
> A-B
[,1] [,2]
[1,] 5 5
[2,] -10 6
Matrix multiplication in R:
Before multiplying two matrices check that the dimensions are compatible. The number of columns of
the first matrix must be equal to the number of rows of the second.
A %*% B
> A %*% B
[,1] [,2]
[1,] 170 78
[2,] 205 87
Element-wise multiplication:
The element-wise multiplication of two matrices of the same dimensions can also be computed with the *
operator. The output will be a matrix of the same dimensions of the original matrices.
A*B
> A*B
[,1] [,2]
[1,] 50 24
[2,] 75 72
R lab Ex4:
Develop a program to find the factorial of given number using recursive function calls.
Example of Recursion
An example can help clarify the concept of recursion. Let us take the example of finding the factorial of a
number.
Factorial of a positive integer number is defined as the product of all the integers from 1 to that number.
For example, the factorial of 5 (denoted as 5!) will be:
This problem of finding factorial of 5 can be broken down into a sub-problem of multiplying the factorial
of 4 with 5.
5! = 5*4!
More generally,
n! = n*(n-1)!
Now we can continue this until we reach 0! which is 1.
Recursive Function in R:
# factorial of 0
recursive.factorial(0)
# factorial of 5
recursive.factorial(5)
# factorial of 7
recursive.factorial(7)
Develop an R Program using functions to find all the prime numbers up to a specified number by the
method of Sieve of Eratosthenes.
# Return the indices of the TRUE values, which are the prime numbers
which(primes)
}
# Example usage
specified_number <- 50
prime_numbers <- find_primes(specified_number)
print(prime_numbers)
This program defines two functions: sieve_of_eratosthenes(n): Implements the Sieve of Eratosthenes
algorithm to find all prime numbers up to n.
find_primes(n): Calls the sieve function and handles edge cases where n is less than 2.
You can change the specified_number variable to any positive integer to find all prime numbers up to that
number.