# Write a function sd that computes the standard deviation of x βfrom scratchβ. Include a parameter na.rm in it
#πΏ(π;π₯)=βππ+πππ(π)β
βπ₯π
# is the log likelihood function of a Poisson variable x with parameter π>0
# Write a function loglikpois with parameters lambda and x (a vector) that computes the log likelihood value for lambda given observations x.
loglikpois <- function(lambda, x) {
#πΏ(π;π₯)=βππ+πππ(π)β
βπ₯π
stopifnot(lambda >= 0, all(x >= 0))
x_int <- as.integer(x)
if (!all(x_int == x)) { # we need a better error message here
stop("all values in x have to be integer values. ")
}
n <- length(x)
-n*lambda + log(lambda)*sum(x)
}
# Make sure to check that lambda is positive; return an error message (using stop()) if it is not.
# Plot the likelihood values for lambda between 0 and 10 for x = c(1, 3, 2, 3, 0, 1, 0, 1, 3, 3)
x = c(1, 3, 2, 3, 0, 1, 0, 1, 3, 3.000, 4)
loglikpois(lambda = 1, x)
loglikpois(lambda = 1.5, x)
library(ggplot2)
ggplot() +
geom_function(fun=loglikpois, args = list(x = x), xlim=c(0, 10))
mean(x)
#############
binom <- function(n, k) {
stopifnot(n >= k, n >= 0, k >= 0)
factorial(n)/(factorial(k)*factorial(n-k))
}
binom2 <- function(n, k) {
stopifnot(n > k, n >= 0, k >= 0)
# get factorial (n-k) out of the denominator
k <- max(k, n-k)
prod((k+1):n)/(factorial(n-k))
}
binom2(10, 5) == choose(10,5)
binom2(175,173)
binom2(175,2)
binom(175,2)
choose(175, 2)Code from class
code
Week02