Created
April 5, 2016 19:14
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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