# MAS115 Class 5 code/solutions # A hand written version of a two-sided t-test # Inputs: x vector of observed data # Outputs: p-value of the test myt.test <- function(x) { n <- length(x) t <- sqrt(n) * (mean(x))/sd(x) pval <- 2 *(1-pt(abs(t), n-1)) return(pval) } #set.seed(11) #x <- rnorm(10, mean = 1) #x <- round(x, digits = 2) #paste(",", x, collapse = "") myt.test a <- c(0.41, 1.03, -0.52, -0.36, 2.18, 0.07, 2.32, 1.62, 0.95, 0) myt.test(a) # Adding more arguments (with a default value) myt.test2 <- function(x, mu = 0) { n <- length(x) t <- sqrt(n) * (mean(x - mu))/sd(x) pval <- 2 *(1-pt(abs(t), n-1)) return(pval) } restest <- myt.test2(a, mu = 1) restest myt.test2(a, 1) myt.test2(mu = 1, x = a) myt.test2(a) myt.test2(a, mu = 0) # Multiple return values with a list myt.test3 <- function(x, mu = 0) { n <- length(x) t <- sqrt(n) * (mean(x - mu))/sd(x) pval <- 2 *(1-pt(abs(t), n-1)) retlist <- list(pval = pval, t = t, signif = (pval < 0.05)) return(retlist) } res2 <- myt.test3(a) res2 res2\$pval ## Local copies of variables do not change external values z <- 5 # Add 10 to a number addten <- function(z) { z <- z + 10 return(z) } addten(z) z # Has not changed the external variable z ## Changing variables by return and reassignment y <- sample(1:100, 10) y y <- sort(y) y ###### Lab tasks ##### ####### Pollution ####### conc <- function(y, z, Q=100, h=50, u=2, sy=10, sz=5) { C <- Q/(2*pi*u*(sz*sy)^0.5)*exp(-0.5*(y^2/sy+(z-h)^2/sz)) return(C) } # Remaining tasks are for handing in!