<- numeric(length = 5)
new new
[1] 0 0 0 0 0
<- c(1,4,6) new_again
R is most suitable for vector based coding. Which means that many tasks that are done element-wise in languages like C/C++ can be done elegantly in R. Below are some exercises to get you started. A new vector can be declared in many ways, below is my default
<- numeric(length = 5)
new new
[1] 0 0 0 0 0
<- c(1,4,6) new_again
One can access elements of a vector by using square brackets:
3] new_again[
[1] 6
Below are some practice questions on this topic.
Write an R code to enumerate the squares of the first 100 natural numbers.
<- 1:100
nums ^2 # R is vectorized nums
A sequence “Dancing Numbers” is defined as follows:
if \(B_n\) is even: \[ B_{n+1} = \dfrac{B_{n}}{2} \]
else
\[
B_{n+1} = 3B_n - 1
\]
Generate the first 100 dancing numbers given \(B_0\) is 13.
<- 13
b0
<- numeric(1e2)
B
for(i in 1:100){
# Even
if (b0%%2 == 0){
<- b0/2
b0 = b0
B[i]
}# Odd
else{
<- 3*b0-1
b0 = b0
B[i]
}
}
B
Write a function in R to calculate the sum of the first n natural numbers. Verify your result with the formula \(\frac{n(n+1)}{2}\)
= function(n)
sum_of_natural_num
{# use for loop to access every number and sum them one by one in a varibale
= 0
sum for (i in 1:n)
{= sum + i
sum
}return(sum)
}
Write a function in R to calculate the arithmetic mean of a vector of numbers.
= function(vec)
arithmetic_mean
{= sum(vec)
sum = sum/length(vec)
Ar_mean return(Ar_mean)
}
# another way
<- function(vec) mean(vec) arithmetic_mean
Write a function in R to calculate the variance of a vector of numbers. The (sample) variance of observations \(x_1, x_2, \dots, x_n\) is
\[\text{Var}(x_1, x_2, \dots, x_n) = \frac{1}{n-1} \sum_{i=1}^{n} (x_i - \bar{x})^2 \,,\]
where \(\bar{x} = n^{-1} \sum_{i=1}^{n} x_i\). Verify with the built-in var()
function.
<- function(x)
calculate_variance
{<- length(x)
n <- mean(x)
mean_x <- sum((x - mean_x)^2) / (n - 1) # we can return values direct also
var_x return(var_x)
}
<- c(1,5,3,8,6,8,5,4)
data calculate_variance(data)
var(data)
Create a vector of the first 500 even integers. Then, calculate the product of all elements in this vector.
# this is the vector
= seq(from = 2, by = 2 , length.out = 500)
even_seq # product of the elements
prod(even_seq)
Define a vector of the first 1000 numbers in :
Arithmetic progression of 7 with common difference of 13. That is, create the sequence \(a_t\) such that \(a_1 = 7\) and \(a_{t+1} - a_{t} = 13\) for all \(t \geq 1\).
<- 7
a1 <- 13
d <- 1000
n <- a1 + (0:(n-1)) * d arithmetic_progression
Geometric progression of 7 with common ratio of 1/13. That is, create the sequence \(a_t\) such that \(a_t = 7\) and \(a_{t+1}/a_t = 1/13\)
<- 7
a1 <- 1/13
r <- a1 * r^(0:(n-1)) geometric_progression
Write a function which generates first n
numbers in Fibonacci sequence.
<- function(n)
fibonacci_sequence
{if (n <= 0) {
return("Enter a natural number")
else if (n == 1) {
} # The first Fibonacci number
return(c(0))
else if (n == 2) {
} # The first two Fibonacci numbers
return(c(0, 1))
}
# Initialize a vector of length n
<- numeric(n)
fib 1] <- 0
fib[2] <- 1
fib[
# Calculate each subsequent Fibonacci number
for (i in 3:n)
{<- fib[i-1] + fib[i-2]
fib[i]
}
# return the sequence
return(fib)
}
# Example usage:
fibonacci_sequence(10)
Create one vector vec1
with \(1^{st}\) 8 odd numbers and vec2
with \(1^{st}\) 8 Fibonacci numbers(remember to start from zero) and then perform the following operations:
element-wise multiplication
element-wise addition
element-wise subtractions (vec1 - vec2
)
element-wise division
elements of vec1
raised to the power of elements of vec2
elements of vec1
modulo elements of vec2
# Define vec1 with the first 8 odd numbers using a loop
<- numeric(8)
vec1 for (i in 1:8)
{<- 2 * i - 1
vec1[i]
}
# Define vec2 with the first 8 Fibonacci numbers using a loop
<- numeric(8)
vec2 1] <- 0
vec2[2] <- 1
vec2[for (i in 3:8)
{<- vec2[i - 1] + vec2[i - 2]
vec2[i]
}
# Print vec1 and vec2 to verify
vec1
vec2
# a. Element-wise multiplication
<- vec1 * vec2
vec_mult
vec_mult
# b. Element-wise addition
<- vec1 + vec2
vec_add
vec_add
# c. Element-wise subtraction
<- vec1 - vec2
vec_sub
vec_sub
# d. Element-wise division
<- vec1 / vec2
vec_div
vec_div
# e. Element-wise exponentiation
<- vec1^vec2
vec_exp
vec_exp
# f. Element-wise modulo operation
<- vec1 %% vec2
vec_mod vec_mod
Do same as question 3 but now vec2
contains only first 4 Fibonacci numbers rest everything is the same. Will it even work or throw error if works then are there any differences you observe after doing same operations?
{r}# Define vec1 with the first 8 odd numbers using a loop
<- numeric(8)
vec1 for (i in 1:8)
{<- 2 * i - 1
vec1[i]
}
# Define vec2 with the first 4 Fibonacci numbers using a loop
<- numeric(4)
vec2 1] <- 0
vec2[2] <- 1
vec2[for (i in 3:4)
{<- vec2[i - 1] + vec2[i - 2]
vec2[i]
}
# NOTICE, NO ERROR!
# Print vec1 and vec2 to verify
vec1
vec2
# a. Element-wise multiplication
<- vec1 * vec2
vec_mult
vec_mult
# b. Element-wise addition
<- vec1 + vec2
vec_add
vec_add
# c. Element-wise subtraction
<- vec1 - vec2
vec_sub
vec_sub
# d. Element-wise division
<- vec1 / vec2
vec_div
vec_div
# e. Element-wise exponentiation
<- vec1^vec2
vec_exp
vec_exp
# f. Element-wise modulo operation
<- vec1 %% vec2
vec_mod vec_mod
Each new term in the Tribonacci Sequence is generated by adding the previous three terms. By starting with \(1, 1 \text{ and } 2\), and considering the terms in the sequence whose values does not exceed \(5\) million, find the sum of all even valued terms.
<- 1
t1 <- 1
t2 <- 2
t3 <- 5000000
mx <- 2
add while(TRUE){
<- t1 + t2 + t3
tn if(tn > mx)
{break
}if(tn %% 2 == 0)
{<- add + tn
add
}<- t2
t1 <- t3
t2 <- tn
t3
} add
Write an R function that takes a numeric vector as input and returns a vector where each element is doubled if it is even, and halved if it is odd.
<- function(vec)
modify_vector1
{<- length(vec)
n <- numeric(length = n)
out
for(i in 1:n)
{if(vec[i] %%2 == 0)
{<- 2*vec[i]
out[i] else{
} <- vec[i]/2
out[i]
}
}return(out)
}
# another method
<- function(vec)
modify_vector2
{# we can do it in one line using sapply
sapply(vec, function(x) if (x %% 2 == 0) x * 2 else x / 2)
}
# Example usage
<- c(1, 2, 3, 4, 5)
vec modify_vector1(vec)
modify_vector2(vec)
Write a function that takes a numeric vector as input and returns the number of elements that are greater than the mean of the vector
<- function(vec)
count_greater_than_mean
{<- mean(vec)
mean_val sum(vec > mean_val)
}
# Example usage
<- c(1, 2, 3, 4, 5, 10, 30)
vec count_greater_than_mean(vec)
Write an R function that generates a vector of the first 100 prime numbers and then returns the vector with only the prime numbers that are also Fibonacci numbers.
# Function to check if prime number
# if it is divisible by any number other than 1 and itself
<- function(n)
is_prime
{if (n <= 1)
{return(FALSE)
}for (i in 2:sqrt(n))
{if (n %% i == 0)
{return(FALSE)
}
}return(TRUE)
}
# Function to generate the first n prime numbers
<- function(n)
generate_primes
{<- numeric(n)
primes <- 0
count <- 2
num while (count < n)
{# check if new number is prime or not
if (is_prime(num))
{<- count + 1
count <- num
primes[count]
}<- num + 1
num
}return(primes)
}
# Function to generate Fibonacci numbers up to a maximum value
<- function(max_val)
generate_fibonacci
{<- c(0, 1)
fibs while (TRUE) {
<- tail(fibs, 2)[1] + tail(fibs, 2)[2]
next_fib if (next_fib > max_val) break
<- c(fibs, next_fib)
fibs
}return(fibs)
}
# Main function to get prime Fibonacci numbers
<- function()
prime_fibonacci_numbers
{# Generate the first 100 prime numbers
<- generate_primes(100)
primes
# Generate Fibonacci numbers up to the maximum prime value
<- max(primes)
max_prime <- generate_fibonacci(max_prime)
fibs
# Get prime Fibonacci numbers
<- primes[primes %in% fibs]
prime_fibs
return(prime_fibs)
}