0% found this document useful (0 votes)
12 views

R Programming

Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views

R Programming

Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 3

R PROGRAMMING

ASSIGNMENT-I

SUBMITTED BY:SUSMITA BAISHYA


REGISTRATION NUMBER:72111378

Write the codes in R programming:


1. Write a function to calculate the factorial of a given number.

factorial_calculate <- function(n) {


if(n == 0 || n == 1) {
return(1)
} else {
return(n * factorial_calculate(n - 1))
}
}

factorial_calculate(5)

2. Create a function to check if a given number is prime or not.

is_prime <- function(n) {


if (n <= 1) {
return(FALSE)
} else if (n == 2) {
return(TRUE)
} else {
for (i in 2:sqrt(n)) {
if (n %% i == 0) {
return(FALSE)
}
}
return(TRUE)
}
}

is_prime(7)

3. Write a program to find the sum of all even numbers between 1 and 100.
sum_even_numbers <- sum(seq(2, 100, by=2))

sum_even_numbers

4. Create a function to calculate the Fibonacci sequence up to a given number of terms.


fibonacci_sequence <- function(n) {
fib <- numeric(n)
fib[1] <- 0
fib[2] <- 1
for (i in 3:n) {
fib[i] <- fib[i-1] + fib[i-2]
}
return(fib)
}

# Example usage:
fibonacci_sequence(10)

5. Write a program to find the transpose of a given matrix.

transpose_matrix <- function(matrix) {


return(t(matrix))
}
matrix_example <- matrix(1:9, nrow=3, byrow=TRUE)
transpose_matrix(matrix_example)

You might also like