rnorouzian
rnorouzian

Reputation: 7517

Making a function more concise in R

I was wondering if there is a way I could write the below function a bit more concisely?

Likelihood = function(x) dnorm(250, mean = x, sd = 10)*dnorm(265, mean = x, sd = 10)*dnorm(259, mean = x, sd = 10)

Upvotes: 1

Views: 57

Answers (1)

Nick Kennedy
Nick Kennedy

Reputation: 12640

You can take advantage of the fact that dnorm is vectorised:

Lik2 <- function(x) prod(dnorm(c(250, 265, 259), x, 10))

If length(x) can be >1L, you'll need to use an alternative version. Using base R:

Lik3 <- function(x) sapply(lapply(x, dnorm, x = c(250, 265, 259), 10), prod)

Using the purrr package:

Lik4 <- function(x) map_dbl(x, ~prod(dnorm(c(250, 265, 259), ., 10)))

However, I suspect your original version is more computationally efficient if x is not scalar.

Upvotes: 7

Related Questions