Wednesday, January 23, 2008

ifelse(o, a, b)

It should be obvious I guess and is also documented, but something that surprised me: length(ifelse(o, a, b)) == length(o). I encountered this in defining the Rice density in R. I have
drice <- function(x, mu, sigmaSq) {
ifelse(x >= 0,
x / sigmaSq *
exp(-(x*x + mu*mu)/(2*sigmaSq))*besselI(x*mu/sigmaSq, 0),
0)
}
Now I wanted to look at the density with a fixed x but multiple values of mu. But for instance drice(1, c(1,2), 1) ==> 0.4657596. What's a good way to handle this? It's pretty ugly, but I think this does what I want:
drice <- function(x, mu, sigmaSq) {
n <- max(length(x), length(mu), length(sigmaSq))
x <- rep(x, length.out=n)
mu <- rep(mu, length.out=n)
sigmaSq <- rep(mu, length.out=n)
ifelse(x >= 0,
x / sigmaSq *
exp(-(x*x + mu*mu)/(2*sigmaSq))*besselI(x*mu/sigmaSq, 0),
0)
}
drice(1, c(1,2), 1) ==> c(0.4657596, 0.1813670) But there has to be a better way.

No comments: