This is an R Markdown document. Markdown is a simple formatting syntax for authoring HTML, PDF, and MS Word documents. For more details on using R Markdown see http://rmarkdown.rstudio.com.
When you click the Knit button a document will be generated that includes both content as well as the output of any embedded R code chunks within the document. You can embed an R code chunk like this:
calc_mean = function(vec) {
# find the mean of a vector
total <- 0
n <- 0
for (i in 1:length(vec)) {
if (!is.na(vec[i])) {
total <- total + vec[i]
n <- n +1
}
avg <- total / n
}
return(avg)
}
calc_median = function(vec) {
# find the median of a vector
# you don't have to write your own sort routine
vec <- sort(vec) # eliminates NAs as a side effect
if (length(vec) == 1) {
med <- vec[1]
}
else if (length(vec) %% 2 == 1) {
# if odd number then pick the middle value
med <- vec[ceiling(length(vec)/2)] # round up
}
else {
# if even compute average of middle 2 numbers
n <- ceiling(length(vec)/2)
med <- (vec[n] + vec[n+1]) /2
}
return (med)
}
# run example
# test-driven development: ALWAYS try out first with some simple, easily verifiable datasets
#vec <- c(1,2,4,5,8)
#vec <- c(1,2,4,5,5,8)
#vec <- c(1,2,4,5,8, NA)
vec <- c(-10:29, NA)
vec
## [1] -10 -9 -8 -7 -6 -5 -4 -3 -2 -1 0 1 2 3 4 5 6
## [18] 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
## [35] 24 25 26 27 28 29 NA
calc_mean(vec)
## [1] 9.5
calc_median(vec)
## [1] 9.5