1 Using a for or while loop, write a function to calculate the number of zeroes in a numeric vector.

vec <- round(runif(10))
z <- 0
for (i in seq_along(vec)) {
  if(vec[i] == 0)
  z <- z + 1
}
print(z)
## [1] 6

2 Use subsetting instead of a loop to rewrite the function as a single line of code.

length(vec[vec==0])
## [1] 6

3

Write a function that takes as input a numeric vector, and returns as output the maximum difference between all possible pairs of elements. Be careful to ensure that your function works properly with both negative and positive numbers. For your first version of the function, create a vector that stores all possible pairwise differences and then extracts the maximum value from that list.

vec <- round(runif(10),2)
#####################################################################################
func1 <- function(myvec=vec){
  
  mat <- matrix(numeric(length(myvec)^2), nrow=length(myvec))

for (i in seq_along(myvec)){
  for (j in seq_along(myvec)){

  mat[i,j] <- myvec[i]-myvec[j]

  }
} 
  z <- c(mat)
  return(list(max(abs(z)),mat))
}
####################################################################################
func1()
## [[1]]
## [1] 0.92
## 
## [[2]]
##        [,1]  [,2]  [,3]  [,4]  [,5]  [,6] [,7]  [,8]  [,9] [,10]
##  [1,]  0.00 -0.02 -0.09  0.32  0.43  0.30 0.83  0.61  0.45  0.06
##  [2,]  0.02  0.00 -0.07  0.34  0.45  0.32 0.85  0.63  0.47  0.08
##  [3,]  0.09  0.07  0.00  0.41  0.52  0.39 0.92  0.70  0.54  0.15
##  [4,] -0.32 -0.34 -0.41  0.00  0.11 -0.02 0.51  0.29  0.13 -0.26
##  [5,] -0.43 -0.45 -0.52 -0.11  0.00 -0.13 0.40  0.18  0.02 -0.37
##  [6,] -0.30 -0.32 -0.39  0.02  0.13  0.00 0.53  0.31  0.15 -0.24
##  [7,] -0.83 -0.85 -0.92 -0.51 -0.40 -0.53 0.00 -0.22 -0.38 -0.77
##  [8,] -0.61 -0.63 -0.70 -0.29 -0.18 -0.31 0.22  0.00 -0.16 -0.55
##  [9,] -0.45 -0.47 -0.54 -0.13 -0.02 -0.15 0.38  0.16  0.00 -0.39
## [10,] -0.06 -0.08 -0.15  0.26  0.37  0.24 0.77  0.55  0.39  0.00

4

Now modify the output of (3) to yield a list with 3 elements. The first list item is the pair of vector values that are the maximum distance apart, the second list item is the pair of numbers representing the position of these elements in the vector, and the third list item is the maximum distance calculated from this pair.

#####################################################################################
func2 <- function(myvec=vec){
  
  mat <- matrix(numeric(length(myvec)^2), nrow=length(myvec), dimnames = list(myvec,myvec))

for (i in seq_along(myvec)){
  for (j in seq_along(myvec)){

  mat[i,j] <- myvec[i]-myvec[j]

  }
} 
   z <- c(mat)
   x <- which(mat==max(abs(mat)), arr.ind=TRUE)
   w<-colnames(mat)[x[1,1]]
   t<-rownames(mat)[x[1,2]]
   h<-mat[x[1,1]]
   k<-mat[x[1,2]]
 
  return(list(c(w,t), x ,max(abs(z))))
}
#####################################################################################
func2()
## [[1]]
## [1] "0.97" "0.05"
## 
## [[2]]
##      row col
## 0.97   3   7
## 
## [[3]]
## [1] 0.92