Midterm:

Event Details:

Allowed material: Calculator + Cheat sheet

Cheat sheet: 1 page recto+verso

Arithmetic and boolean operations

You must know the symbols used for basic operations in R

You must be able to execute code mentally (in your head)

You can use a calculator to help you evaluate some expressions

##Arithmetic operations

Please revise the meaning of arithmetic operations in R

Understand the priority of operators and order of evaluation of expressions without parenthesis in R:

7/8/9/10
## [1] 0.009722222
-6^2
## [1] -36
-2^1/2
## [1] -1
27 ^ (1/3)
## [1] 3
7/8/9 == (7/8)/9
## [1] TRUE
x = c(8,4,3,7,9,0)

mysum=0

for(i in 1:length(x)){
  mysum=mysum+i
}
mysum
## [1] 21
x = c(8,4,3,7,9,0)

my=0

for(i in 1:length(x)){
  my=my+x[i]-3
}
my
## [1] 13
x = c(8,4,3,7,9,0)
y = c(4,2,6,9,1,3)
ifelse(x>=y,x,y)
## [1] 8 4 6 9 9 3

identify which arrays are going to change and which are not

myf = function(x,y){
  
out  = y^3

for(i in 1:length(x)){
 # print(c(i,y[i],x[i]))
  if(y[i] > x[i])out[i] = x[i]^2 
  }

return(out)
}
u <- c(0,1,2)
v <- c(5,2,1)
myf(u,v)
## [1] 0 1 1
x = c(8,4,3,7,9,0)
y = c(4,2,6,9,1,3)
ifelse(x>=y,y-x,x+2*y)
## [1] -4 -2 15 25 -8  6

##Boolean operations

Understand the meaning of logical (boolean) operators.

precedence of operators in R

Precedence and Associativity of different operators in R from highest to lowest

Operator Precedence in R
Operator Description Associativity
^ Exponent Right to Left
-x, +x Unary minus, Unary plus Left to Right
%% Modulus Left to Right
*, / Multiplication, Division Left to Right
+, – Addition, Subtraction Left to Right
<, >, <=, >=, ==, != Comparisions Left to Right
! Logical NOT Left to Right
&, && Logical AND Left to Right
|, || Logical OR Left to Right
->, ->> Rightward assignment Left to Right
<-, <<- Leftward assignment Right to Left
= Leftward assignment Right to Left
x=F
y=T

!x&y
## [1] TRUE
x=F
y=F
z=T

x&y|z  == x|y&z
## [1] FALSE
(x&y) | z == x&y|z  # ambiguity !!!
## [1] TRUE
x|y&z == x|(y&z)    # careful !!!!
## [1] FALSE
x | y&z
## [1] FALSE
x | (y&z)
## [1] FALSE
(x|y&z) == (x | (y&z))
## [1] TRUE

8 ^ (1/3)

# to assign the boolean value TRUE to a boolean variable x, you write
x=T
# same idea for the boolean value FALSE
y=F
t=T
z=F
u=T
w=T
q=F
m=T
# this calculates x OR y
x | y
## [1] TRUE
# this calculates y AND z
y & z
## [1] FALSE
# because AND has priority over OR
# when there is no parenthesis, the expression
x&y|z
## [1] FALSE
# is evaluated like this
(x&y)|z
## [1] FALSE
# which means that you first calculate x&y , store it in r, then calculate r | z
# when you have blocks of consecutive &, such blocks are F except if all variables in the block are T
# what is the value of
x&y&t&u
## [1] FALSE
# opposite for or. for a block of or, the block is T except if all variables in the block are F
q|m|y|t
## [1] TRUE
# can you MENTALLY (in your head) predict the value of the following expression, then run R
# and check if you are right?
x|y&z|t&u&w|q|m
## [1] TRUE

Vectors and matrices

You must know how to:
v <- c(3,6,8,2,9,1)

n=length(v)
n
## [1] 6
#accessing vectors

#value of c and access

i=0
i=2
c(v[i],v[i+1],v[i+2])
## [1] 6 8 2
# storing results in vectors
# certain operations or functions return not a single value but a vector or list of values

# what does the function sort return if we apply it to a vector/list?

 sort(v)
## [1] 1 2 3 6 8 9
 w <- c('c','a','d','b')
 sort(w)
## [1] "a" "b" "c" "d"

EXERCISE-MATINIT

You must know how to define a matrix and assign numerical values to it, either via the matrix function, or via a for loop

W=matrix(1:16,byrow=T,ncol=4)
W
##      [,1] [,2] [,3] [,4]
## [1,]    1    2    3    4
## [2,]    5    6    7    8
## [3,]    9   10   11   12
## [4,]   13   14   15   16
# you must understand all these examples of initialization of a matrix
A=matrix(1:15,byrow=T,ncol=3)
A
##      [,1] [,2] [,3]
## [1,]    1    2    3
## [2,]    4    5    6
## [3,]    7    8    9
## [4,]   10   11   12
## [5,]   13   14   15
B=matrix(1:15,byrow=T,nrow=3)
B
##      [,1] [,2] [,3] [,4] [,5]
## [1,]    1    2    3    4    5
## [2,]    6    7    8    9   10
## [3,]   11   12   13   14   15
# to fill a matrix by columns you do not use bycol, but you specify byrow=F
C=matrix(1:15,byrow=F,nrow=3) # shoot  not bycol=T
C
##      [,1] [,2] [,3] [,4] [,5]
## [1,]    1    4    7   10   13
## [2,]    2    5    8   11   14
## [3,]    3    6    9   12   15
D=matrix(1:15,byrow=F,ncol=3)
D
##      [,1] [,2] [,3]
## [1,]    1    6   11
## [2,]    2    7   12
## [3,]    3    8   13
## [4,]    4    9   14
## [5,]    5   10   15
# use this as a generic way to define a zero matrix with given number of rows and columns
E=matrix(0,nrow=3,ncol=5)
E
##      [,1] [,2] [,3] [,4] [,5]
## [1,]    0    0    0    0    0
## [2,]    0    0    0    0    0
## [3,]    0    0    0    0    0
M=matrix(0,nrow=5,ncol=3)
# to retrieve the number of rows and columns of a matrix M
n = nrow(M)
m = ncol(M)
c(n,m)
## [1] 5 3

Please see the loop section if you do not understand loops

replace all matrix elements by j if divisible by 5 and by i if not divisible by 5

M=matrix(0,nrow=5,ncol=3)
# to retrieve the number of rows and columns of a matrix M
n = nrow(M)
m = ncol(M)
c(n,m)
## [1] 5 3

Here I use loops to ‘scan’ all column and row indexes and assign a value to the generic matrix element \(M(i,j)\).

Can you run the following code on the paper?

M=matrix(0,nrow=5,ncol=3)
# to retrieve the number of rows and columns of a matrix M
n = nrow(M)
m = ncol(M)
x <- c(2,4,6,8,10)
y <- c(10,20,30)

# initialize the vector x of angles
# x <-c(...)
# initialize the vector y of functions

for (i in (1:n)){
for (j in (1:m)){
#  M[i,j] = myfct(x[i],y[j])
  M[i,j] = x[i]* y[j]
}
}
M
##      [,1] [,2] [,3]
## [1,]   20   40   60
## [2,]   40   80  120
## [3,]   60  120  180
## [4,]   80  160  240
## [5,]  100  200  300

Let us explore a variant of this exercise

for example , suppose I want to calculate the sine, the cosine and the tangent of 5 angles, (say : 10,15,20,45,60 degrees) How would you tabulate these values using the receipe I just suggested?

As the base trigonometric function (sin, cos, tan) expect angles expressed in radians (there are \(\pi\) radians in \(180\) degrees),you may want to fisrt code a function that transforms degrees to radians:

degrees.to.radians<-function(degrees=45,minutes=30)
{
if(!is.numeric(minutes)) stop("Please enter a numeric value for minutes!\n")
if(!is.numeric(degrees)) stop("Please enter a numeric value for degrees!\n")
  
  
#print(degrees)  
  
  
decimal<-minutes/60
c.num<-degrees+decimal
radians<-c.num*pi/180
radians
}

# lets check this on 45 degrees. what should this return?
tan(degrees.to.radians(45.,0))
## [1] 1
# yes R has already a function to do this
tanpi(45)
## [1] 0

Now let us capitalize on this function, and write a new function that will calculate the values for any matrix element (row-column numbers)

myfct = function(x,y){
  
radangle = degrees.to.radians(x,0);
if(y == 1){
  s = sin(radangle);
  return(s)
}
if(y == 2){
  c = cos(radangle);
  return(c)
}  
if(y == 3){
  t = tan(radangle);
  return(t)
}  

}
mytrigotable = function(M,x,y){
n=nrow(M)
m=ncol(M)
for (i in (1:n)){
  for (j in (1:m)){
    # print(c(x[i],y[j]))
    M[i,j] = myfct(x[i],y[j])
  }
}
return(M)
}
x =   c(10,30,45,60,80)
y =   c(1,2,3)
M=matrix(0,byrow=T,ncol=3,nrow=5)

mytrigotable(M,x,y)
##           [,1]      [,2]      [,3]
## [1,] 0.1736482 0.9848078 0.1763270
## [2,] 0.5000000 0.8660254 0.5773503
## [3,] 0.7071068 0.7071068 1.0000000
## [4,] 0.8660254 0.5000000 1.7320508
## [5,] 0.9848078 0.1736482 5.6712818

EXERCICE-SAME

we frequently use assignments instructions in which the same variable is used on the left and the right hand side

You must understand that in such an assignment of the form \(x = f(x)\), the variable \(x\) on the right has an ‘old’ value that is frozen during the calculation, \(x=f(x_{old})\), and after evaluating \(f\), the result of the operation overwrites \(x\).

We will see later an example where \(x\) is modified in this way at each iteration within a loop.

x=c(T,T,F,T,F) # initial value 
x
## [1]  TRUE  TRUE FALSE  TRUE FALSE
x[3 ] = x[2] | x[5]  # modification of the form $x=f(x)$
x                    # print the result: new value of x
## [1]  TRUE  TRUE  TRUE  TRUE FALSE
x[3 ] = x[1] & x[4]
x
## [1]  TRUE  TRUE  TRUE  TRUE FALSE
x[3 ] = x[3] | x[2]
x
## [1]  TRUE  TRUE  TRUE  TRUE FALSE
x[3 ] = x[1] & x[5]
x
## [1]  TRUE  TRUE FALSE  TRUE FALSE

Conditional instructions

Understand how the ifelse command works on vectors

Basically :

ifelse(CONDITION,RESULTIFTRUE,RESULTIFFALSE)

in returns a vector that is ‘composite’. This vector takes the value of the vector at those places where CONDITION evaluates to

or else

Understand how to run R code mentally or on the paper

understand what is returned by a function upon calling it with knpwn arguments values exemple

x=c(T,T,F,T,F)
rT = c(1,2,3,4,5)
rF = c('a','b','c','d','e')
ifelse(x,rT,rF)
## [1] "1" "2" "c" "4" "e"

EXERCICE-INYOURHEAD

Can you run the following code ‘in your head’, and guess what z will be?

After guessing the value of z, rerun this code with z printed out

x=   c(5,2,7,8,9,4,31)
rT = x%%3 < 2
rF = c('hello','this','is','a','nice','exercise','!')
z <- ifelse(x%%3 < 2,rT,rF)
#z

Loops

You must be able to run/execute a small loop in your head or with pen and paper

Exercice: follow how a vector \(x\) is modified a loop:

Can you run this code in your head and predict the output?

x=c(T,T,F,T,F)

for (i in 1:5){
  if(i > 1 & i < 5){
     x[i ] = x[i-1] & x[i+1] & x[i]
     
     print(x)
  }
}
## [1]  TRUE FALSE FALSE  TRUE FALSE
## [1]  TRUE FALSE FALSE  TRUE FALSE
## [1]  TRUE FALSE FALSE FALSE FALSE

Can you run this code in your head and predict the output?

x=c(T,T,F,T,F)

for (i in 1:5){
  if(i > 1 & i < 5){
     x[i ] = x[i-1] & x[i+1] & x[i]
     
     print(x)
  } 
  else if(i < 5){
     x[i] = !x[i] | !x[i+1]
  }
}
## [1] FALSE FALSE FALSE  TRUE FALSE
## [1] FALSE FALSE FALSE  TRUE FALSE
## [1] FALSE FALSE FALSE FALSE FALSE

Functions

You must understand how to define your own functions, and how to call a function.

You must understand how to see which values are returned by a function

# if you see this in the function, it means that the function returns the values
# of the variables x y  and t, provided this statement is executed
# return(x,y,t)

You must be able to run a simple function ‘on the paper or in your head’, given values of the arguments.

Exercice: runfunctioninhead

Can you predict on the paper what will be printed?

  fme=function(x){
    n=length(x)
    for (i in (1:(n-1))){
        # suppose that 
        x[i] = x[i+1]+x[i]
}
   return(x)
}


x=c(7,2,-1,4,-5,8)
# this will print the result returned by the function for the specified value of the argument x

fme(x)
## [1]  9  1  3 -1  3  8

You must understand that functions can return more than a single value

For example, the function sort applied to a vector returns a vector

Can you guess the output of this code:

x  =c(7,2,-1,4,-5,8)
z = sort(x) # z is returned by the function sort. what is z?
# guess the value of z

Can you guess the output of this code (run in your head)

x=c(7,2,-1,4,-5,8)
i=2
x[i:(i+1)] = c(x[i+1],x[i])
# can you guess what will be printed here
print(x)
## [1]  7 -1  2  4 -5  8

When you try to predict the output of a loop, please just execute the loop by freezing the values of the index and do the necessary calculations in the body of the loop.

Please do this exercise: run the following loop on the paper, then check that your result is right by running R.

W=matrix(1:16,byrow=T,ncol=4)
print(W)
##      [,1] [,2] [,3] [,4]
## [1,]    1    2    3    4
## [2,]    5    6    7    8
## [3,]    9   10   11   12
## [4,]   13   14   15   16
fmat=function(W){
n=nrow(W)
    
      for (i in 1:n){
      for (j in 1:n){
        
        W[j,i]=W[i,j]+W[j,i]
        
        print(c(i,j,W[i,j]))
        
        #paste("wij  ",w[i,j]," i,j = ",i,j)
        
        #pass i=1, j=1
        #11  = 11+11 # 11 will not be reused here
        #21  = 12+21
        #31  = 13+31
        #41  = 14+41
        
      }
      }
    
      return(W)
}

print(fmat(W))
## [1] 1 1 2
## [1] 1 2 2
## [1] 1 3 3
## [1] 1 4 4
## [1] 2 1 7
## [1]  2  2 12
## [1] 2 3 7
## [1] 2 4 8
## [1]  3  1 12
## [1]  3  2 17
## [1]  3  3 22
## [1]  3  4 12
## [1]  4  1 17
## [1]  4  2 22
## [1]  4  3 27
## [1]  4  4 32
##      [,1] [,2] [,3] [,4]
## [1,]    2    9   15   21
## [2,]    7   12   24   30
## [3,]   12   17   22   39
## [4,]   17   22   27   32

goes in but not out

a=2
b=1
x=2
me=function(x){
b=2
a=a+1
print(a)
output=a*(x+b)
return(output)
}

me(x)
## [1] 3
## [1] 12
a
## [1] 2
a=2
b=1
x=5
me=function(x){
b=2
print(a)
output=a*(x+b)
return(output)
}

me(x)
## [1] 2
## [1] 14
a
## [1] 2
my=function(W){
n=nrow(W)
for (i in 1:n){
for (j in 1:n){
  
W[j,i]=W[i,j]

print(W)

}}
return(W)
}

W=matrix(1:9,byrow=T,ncol=3)
W
##      [,1] [,2] [,3]
## [1,]    1    2    3
## [2,]    4    5    6
## [3,]    7    8    9
my(W)
##      [,1] [,2] [,3]
## [1,]    1    2    3
## [2,]    4    5    6
## [3,]    7    8    9
##      [,1] [,2] [,3]
## [1,]    1    2    3
## [2,]    2    5    6
## [3,]    7    8    9
##      [,1] [,2] [,3]
## [1,]    1    2    3
## [2,]    2    5    6
## [3,]    3    8    9
##      [,1] [,2] [,3]
## [1,]    1    2    3
## [2,]    2    5    6
## [3,]    3    8    9
##      [,1] [,2] [,3]
## [1,]    1    2    3
## [2,]    2    5    6
## [3,]    3    8    9
##      [,1] [,2] [,3]
## [1,]    1    2    3
## [2,]    2    5    6
## [3,]    3    6    9
##      [,1] [,2] [,3]
## [1,]    1    2    3
## [2,]    2    5    6
## [3,]    3    6    9
##      [,1] [,2] [,3]
## [1,]    1    2    3
## [2,]    2    5    6
## [3,]    3    6    9
##      [,1] [,2] [,3]
## [1,]    1    2    3
## [2,]    2    5    6
## [3,]    3    6    9
##      [,1] [,2] [,3]
## [1,]    1    2    3
## [2,]    2    5    6
## [3,]    3    6    9

<a href="https://www.guru99.com/r-apply-sapply-tapply.html?>apply-sapply-lapply-tapply