Instantly share code, notes, and snippets.

Embed
What would you like to do?
Demo files for R related blog post: Time is TRUE, Female is FALSE
# correctanswer.R: sourcing this file in a fresh R session gives the correct answer = 5.
source("oddmean.R")
y <- 1:10
correct.answer <- oddmean(y)
print(correct.answer)
# oddmean.R
#' @title Mean of odd numbered elements of x
#' @param x numeric vector
oddmean <- function(x) {
# We use vector recycling rules of R here
# See http://www.perfectlyrandom.org/2015/06/16/never-trust-the-row-names-of-a-dataframe-in-R/
mean(x[c(T, F)])
}
# redefine.R
T <- 1:4
F <- 3
# wronganswer1.R: sourcing this file in a fresh R session gives the wrong answer = 2.
source("oddmean.R")
T <- 1:3
y <- 1:10
wrong.answer1 <- oddmean(y)
print(wrong.answer1)
# wronganswer2.R: sourcing this file in a fresh R session gives the wrong answer = 2.6.
source("oddmean.R")
source("redefine.R")
source("correctanswer.R")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment