1. Using a for or while loop, write a function to calculate the number of zeroes in a numeric vector.
m <- c(0,0,0,1,2,3,4,5)
vec <- vector(mode = "numeric")
for (i in seq_along(m)) {
if (m[i]==0) (vec[i] <- 1) else
if (m[i] != 0) (vec[i] <- 0)
}
sum(vec)
## [1] 3
2. Use subsetting instead of a loop to rewrite the function as a single line of code.
m <- c(0,0,0,1,2,3,4,5)
vec2 <- sum(m==0)
vec2
## [1] 3
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
#################################################################################
##################################################
# FUNCTION: MaxDif2 ** From Alex Burnham **
# max difference between pair of elements in vector
# input: numeric vector
# output: list of three elements
#-------------------------------------------------
MaxDif2 <- 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))))
}
#####################################################################################
MaxDif2()
## [[1]]
## [1] "0.93" "0.01"
##
## [[2]]
## row col
## 0.93 6 2
##
## [[3]]
## [1] 0.92