For loop to calculate the number of zeros in a vector:

#Create a numeric vector
Vec1 <- round(runif(10))
x <- 0

for ( i in seq_along(Vec1)) {
  if (Vec1[i] == 0)
    x <- 1 + x
}
print(x)
## [1] 3

Use subsetting to rewrite function as a single line of code

x <- length(subset(Vec1,Vec1==0))
x
## [1] 3

Create a function that makes a vector that stores all possible pairwise differences and then extracts the maximum value from the list

vec2 <- round(runif(10),2)

returnMaxDiff <- function(myvec=vec2){
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]

}
} 
x <- c(mat)
return(list(max(abs(x))))
}

returnMaxDiff()
## [[1]]
## [1] 0.77

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.

returnMaxDiff <- function(myvec=vec2){
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]

}
} 
x <- c(mat)
p <- (which(mat == max(abs(mat)), arr.ind=TRUE))
name1 = rownames(mat)[p[,1]]
name2 = rownames(mat)[p[,2]]
m <- (max(abs(x)))

return(cat(name1, name2 , p, m))
}

returnMaxDiff()
## 0.85 0.08 5 4 0.77