# R中的MLE（多参数功能）MLE in R (multiple parameter function)

``````likelihood <- function(N, p){
likelihood <- 1
X <- 0
for (s in 1:S){
X <- X + M[s]
}
likelihood <- likelihood * p^(X) * (1-p)^(N*S-X)
likelihood <- likelihood * (factorial(N)/factorial((N-length(U))))
return(likelihood)
}
``````

`````` captures <- function(N, S, P){
P <- replicate(S, P) #Capture Probability (same across animals and surveys)
captures <- t(replicate(N, rbinom(S, 1, P))) #Generate capture data from N animals with S surveys with capture Probability P
return(captures)
}

marked <- function(N, S, captures){ #Count numbers that were marked on each survey
M <- replicate(S, 0) #Initialise the 'marked' variable to zero
for (s in 1:S){
for (i in 1:N){
if (captures[i, s] == 1){
M[s] <- M[s] + 1
}
}
}
return(M)
}

unseen <- function(N, S, captures){#Count total number of animals that were unseen on any survey
U <- array()
seen <- replicate(N, FALSE) #All animals begin as unseen
for (i in 1:N){
for (s in 1:S){
if (captures[i, s] == 1){
seen[i] = TRUE
}
}
if (seen[i] == FALSE){
U <- c(U, i)
}
}
U <- U[-1] #fix the N/A in the first index
return(U)
}

firstcaught <- function(N, S, captures){#Produce a vector containing how many animals were   caught for the first time on each survey
fc <- 0
seen <- replicate(N, FALSE)
for (s in 1:S){
fc[s] <- 0
for (i in 1:N){
if ((seen[i] == FALSE) && (captures[i, s] == 1)){
fc[s] <- fc[s] + 1
seen[i] = TRUE
}
}
}
return(fc)
}

##Generate data using functions
N <- 200
S <- 10
P <- 0.2
n <- captures(N,S,P)
M <- marked(N,S,n)
U <- unseen(N,S,n)
fc <- firstcaught(N,S,n)
Mc <- cumsum(fc) #A running total of animals that have been captured at least once

##Define a likelihood for model M_0
likelihood <- function(N, P){
likelihood <- 1
X <- 0
for (s in 1:S){
X <- X + M[s]
likelihood <- likelihood * (1-P)^(N-M[s])
likelihood <- likelihood * choose(N-M[s],fc[s])
}
likelihood <- likelihood * P^(X) * (1-P)^(-X)
return(-log(likelihood))
}

##Find the MLE
out <- nlm(f = likelihood, p = 200, P = P, check.analyticals = TRUE)
``````

1回复

1回复

1回复

1回复

1回复

1回复

1回复

1回复

2回复

1回复