N.B.: before starting any exercise that involves random numbers, set the seed to 1303 (i.e., execute set.seed(1303))
# Ex 1:
#Given a number n, generate a list containing the first
# n integer numbers starting from 5.
#Class solution:
n = 30
lista = seq(5,n+5-1)
lista
# Class solution:
n = 4
v<-seq(5,5+n)
v
# Solution
n <-6
seq(5,5+n)
# Alternative
n <-6
ls2 <- list(5:(n+5))
print(ls2)
ls3 <- c(5:(n+5))
print(ls3)
# Ex 2: Given two numbers a and b,
# compute the sum of the numbers between a and b.
a = 3
b = 7
sum = 0
for(e in a:b){
sum = sum + e
}
print(sum)
# Class solution:
a = 2
b = 5
#(a+1):(b-1)
sum(seq(a,b))
# Solution
a <- 5
b <- 10
sum(a:b)
#Ex 3:
#Given a number n, compute the factorial of n.
#The factorial of a number n can be defined as product
# of all positive numbers less than or equal to n.
n = 3
fac = 1
while(n>0){
fac = fac * n
n = n -1
}
print(fac)
# Class solution:
n <- 5
a <- 1
f <- seq(1:n)
for(i in f){
a <- a*i
}
print(a)
# Solution
n <- 5
f <- 1
while(n>1){
f <- f * n
n <- n - 1
}
f
# Alternative
n = 5
f = n
i = 0
while(i < n-1){
i = i+1
f = f*i
}
f
# Alternative
f = 1
for(i in (1:n)){
f = f * i
}
f
#Ex 4:
# Consider a vector x <- c(4,5,8,10,3,5,13), what is the value of x < 7 ?
x <- c(4,5,8,10,3,5,13)
x < 7
x <- c(4,5,8,10,3,5,13)
x < 7
#Ex 4 (bis):
# print the values of x that are lower than 7
x <- c(4,5,8,10,3,5,13)
for(el in x){
if(el<7){
print(el)
}
}
#Alternative solution
print(x[x<7])
for(i in x){
if(i<7)
print(i)
}
# Solution 1
for(i in x){
if(i<7)
print(i)
}
# Solution 2
#test <- x<7
#x[test]
# ... or directly...
x[x<7]
?seq
#Ex 5:
#(define a code that is able to...) Create a list with all odd numbers in the even positions
# and vice-versa.
input <- x
e <- input[input %% 2 == 0] # TRUE in the even positions
o <- input[input %% 2 != 0] # TRUE in the odd positions
l <- c()
i <- 1
j <- 1
while(i<=length(input)){
l = append(l,e[j])
l = append(l,o[j])
i = i + 2
j = j + 1
}
print(l)
a <- seq(1,10)
ls <-seq(2,10,2)
a[ls] = ls-1
a[ls-1] = ls
print(a)
# and the winner is...
ls <-seq(2,10)
ls
# Solution
ls <- list(2,2,2,2,2,2,2)
n <- length(ls)
cnt <- 2
repeat{
ls[cnt] <- 1
cnt = cnt + 2
if(cnt>=n)
break
}
ls
# More challenging way...
x <- seq(1:9)
j <- 1
i = 1
n = length(x)
while(i < n+1){
x[i] = x[i] +1
i = i +1
}
x