Skip to content

Instantly share code, notes, and snippets.

@jarad
Created April 5, 2016 19:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jarad/65e9dd5a96da271ac3d12459ab0b234b to your computer and use it in GitHub Desktop.
Save jarad/65e9dd5a96da271ac3d12459ab0b234b to your computer and use it in GitHub Desktop.
Example usage of the Vectorize() function in R for evaluation of a likelihood surface for multiple values of the parameter
y = rnorm(5)
log_like = function(theta, y) {
sum(dnorm(y,theta,log=TRUE))
}
thetas = c(1,2)
# Evaluating the theta vector one at a time works,
log_like(thetas[1],y)
log_like(thetas[2],y)
# but evaluating the vector theta does not give the
# desired result, i.e. a vector of log_likelihood values
log_like(thetas,y)
# See, they aren't equal
all.equal(c(log_like(thetas[1],y),
log_like(thetas[2],y)),
log_like(thetas,y))
################################################
# But we can vectorize the function
vlog_like = Vectorize(log_like, vectorize.args='theta')
# and now it works as desired
all.equal(c(vlog_like(thetas[1],y),
vlog_like(thetas[2],y)),
vlog_like(thetas,y))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment