使用非整数数据的多项式密度函数?
Multinomial density function working with non-integer data?
有谁知道为什么 R 中的 dmultinom 函数适用于非整数,在那种情况下 return 有什么作用?见下文:
> dmultinom(c(0.7,0.1,0.1,0.1) ,prob = c(0.25,0.25,0.25,0.25))
[1] 0.25
> dmultinom(c(0.25,0.25,0.25,0.25) ,prob = c(0.25,0.25,0.25,0.25))
[1] 1
这是dmultinom
的源代码
function (x, size = NULL, prob, log = FALSE)
{
K <- length(prob)
if (length(x) != K)
stop("x[] and prob[] must be equal length vectors.")
if (any(!is.finite(prob)) || any(prob < 0) || (s <- sum(prob)) ==
0)
stop("probabilities must be finite, non-negative and not all 0")
prob <- prob/s
x <- as.integer(x + 0.5)
if (any(x < 0))
stop("'x' must be non-negative")
N <- sum(x)
if (is.null(size))
size <- N
else if (size != N)
stop("size != sum(x), i.e. one is wrong")
i0 <- prob == 0
if (any(i0)) {
if (any(x[i0] != 0))
return(if (log) -Inf else 0)
if (all(i0))
return(if (log) 0 else 1)
x <- x[!i0]
prob <- prob[!i0]
}
r <- lgamma(size + 1) + sum(x * log(prob) - lgamma(x + 1))
if (log)
r
else exp(r)
}
如您所见,它将 x
舍入为 x <- as.integer(x + 0.5)
中最接近的整数。
因此,在您的情况下,它相当于:
dmultinom(c(0,0,0,0) ,prob = c(0.25,0.25,0.25,0.25))
[1] 1
有谁知道为什么 R 中的 dmultinom 函数适用于非整数,在那种情况下 return 有什么作用?见下文:
> dmultinom(c(0.7,0.1,0.1,0.1) ,prob = c(0.25,0.25,0.25,0.25))
[1] 0.25
> dmultinom(c(0.25,0.25,0.25,0.25) ,prob = c(0.25,0.25,0.25,0.25))
[1] 1
这是dmultinom
function (x, size = NULL, prob, log = FALSE)
{
K <- length(prob)
if (length(x) != K)
stop("x[] and prob[] must be equal length vectors.")
if (any(!is.finite(prob)) || any(prob < 0) || (s <- sum(prob)) ==
0)
stop("probabilities must be finite, non-negative and not all 0")
prob <- prob/s
x <- as.integer(x + 0.5)
if (any(x < 0))
stop("'x' must be non-negative")
N <- sum(x)
if (is.null(size))
size <- N
else if (size != N)
stop("size != sum(x), i.e. one is wrong")
i0 <- prob == 0
if (any(i0)) {
if (any(x[i0] != 0))
return(if (log) -Inf else 0)
if (all(i0))
return(if (log) 0 else 1)
x <- x[!i0]
prob <- prob[!i0]
}
r <- lgamma(size + 1) + sum(x * log(prob) - lgamma(x + 1))
if (log)
r
else exp(r)
}
如您所见,它将 x
舍入为 x <- as.integer(x + 0.5)
中最接近的整数。
因此,在您的情况下,它相当于:
dmultinom(c(0,0,0,0) ,prob = c(0.25,0.25,0.25,0.25))
[1] 1