<- c(1, 2, 3, 4)
vec.a * 2 vec.a
[1] 2 4 6 8
RaukR 2023 • Advanced R for Bioinformatics
Marcin Kierczak
21-Jun-2024
In programming languages loop structures, either with or without conditions, are used to repeat commands over multiple entities. For and while loops as well as if-else statements are also often used in R, but perhaps not as often as in many other programming languages. The reason for this is that in R, there is an alternative called vectorization which usually is more efficient.
Vectorization implies that we can multiply all values in a vector in R by two by calling:
In many other and languages as well as in R, you can also create this with a loop instead
As you saw in the lecture, this is far less efficient and not by any means easier to type and we hence tend to avoid loops when possible.
for
-loop that calculates the sum for each row of the matrix.apply()
functionapply()
function rowSums()
function[1] 4500010 4500020 4500030 4500040 4500050 4500060
[1] 4500010 4500020 4500030 4500040 4500050 4500060
[1] 4500010 4500020 4500030 4500040 4500050 4500060
[1] TRUE
[1] FALSE
[1] TRUE
During the lecture an approach to calculate factorials was implemented using recursion (function calling itself). Here we should use recursion to generate a sequence of Fibonacci numbers. A Fibonacci number is part of a series of number with the following properties:
0, 1, 1, 2, 3, 5, 8, 13, 21, ...
or
1, 1, 2, 3, 5, 8, 13, 21, ...
Write a function that generates Fibonacci number using a recursive approach.
Generate Fibonacci numbers from 0 to 10 using *apply*
approach.
Vectorize your Fibonacci number generating function.