简体   繁体   中英

How to write this function for mixture model in R?

I want to want to estimate a model in R .

One of its part is a finite mixture model which is consisted of two OLS .

As a freshman in R, I don't know how to write this probability density function in R.

I wonder if you can give some help.

The probability density function is as following:

f(y|x)=(p/σ1)*φ(y-x*b1/σ1)+((1-p)/σ2)*φ(y-x*b2/σ2)

I have used stata to write a example:

 
   gen double f1'=normalden($ML_y1,xb1',exp(lns1')) gen doublef2'=normalden($ML_y1,xb2',exp(lns2'))
   tempvar p
   gen double p'=exp(lp')/(1+exp(lp')) replacelnf'=ln(p'*f1'+(1-p')*f2') 
   

I wonder if you can show me how to write this function in R.

Thanks a lot and I am looking forward to your help

See the function FLXMRglm . The density is estimated with dnorm

library(flexmix)
FLXMRglm

# your case 


if (family == "gaussian") {
        z@defineComponent <- function(para) {
            predict <- function(x, ...) {
                dotarg = list(...)
                if ("offset" %in% names(dotarg)) 
                  offset <- dotarg$offset
                p <- x %*% para$coef
                if (!is.null(offset)) 
                  p <- p + offset
                p
            }
            logLik <- function(x, y, ...) dnorm(y, mean = predict(x, 
                ...), sd = para$sigma, log = TRUE)
            new("FLXcomponent", parameters = list(coef = para$coef, 
                sigma = para$sigma), logLik = logLik, predict = predict, 
                df = para$df)
        }
        z@fit <- function(x, y, w, component) {
            fit <- lm.wfit(x, y, w = w, offset = offset)
            z@defineComponent(para = list(coef = coef(fit), df = ncol(x) + 
                1, sigma = sqrt(sum(fit$weights * fit$residuals^2/mean(fit$weights))/(nrow(x) - 
                fit$rank))))
        }
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM