R Markdown
#1 and #2 write two functions that takes in a numeric vector and determin the mean and the median from the values in the vector without using the mean() and median() functions.
# set seed to show the same results
set.seed(1998)
# generate a random sample between 1 and 50 with size 15
vect <- sample(1:50, size = 15)
mean_func <- function(x) {
if (!is.numeric(x)) {
stop("Argument vector must be numeric")
}
# takes the total sum of values in the vector and divides it with its length
return (sum(x) / length(x))
}
median_func <- function(x) {
# checks whether input vector is numeric
if (!is.numeric(x)) {
stop("Argument vector must be numeric")
}
# sorts the numeric vector just in case it is not sorted
y <- sort(x)
n <- length(x)
# checks whether the lenght of the vector is odd
if (n %% 2 != 0) {
# if the length is odd then it returns the middle number
return (y[(n + 1) / 2])
} else {
# if the length is even then it returns the mean of the two middle numbers
return ((y[n / 2] + y[(n + 1) / 2]) / 2)
}
}
mean_func(vect)
## [1] 25.46667
median_func(vect)
## [1] 24