2
$\begingroup$

I am relatively new to R and GLMs. I have a simple GLM y ~ a+b. a is the dominant variable and I would like the coefficients to basically give more weight to a and then use b to explain the remainder. I have created a simplified example to illustrate a problem I am running into. The coefficient with variable "b" is not aligning with expectations due to mix differences in variable "a" within the data. I'm probably doing something wrong. In my actual data, tweedie is the right model, so I used it for this made-up data, however it probably isn't the right fit here. Hopefully this still illustrates what I am trying to do. I've looked at R help for offsets and weights and I still don't understand how to use them correctly. I am copying the form of a tweedie GLM I saw used in a presentation. So, what do I need to do to get this GLM to accurately recognize that if b = 3, the coefficient should be 1.5 and if b = 2, the coefficient should be 1.0?

##  example ##############################

a <- 1:20
a[1:10] <- a[1:10]* 100
a[11:20] <- a[1:10] * 100
# true coef
a_coef <- 0.2

b <- 1:20
b[1:10] <- 3 # true coef = 1.5
b[11:20] <- 2 # true coef = 1.0

# true formula for y
y <- a_coef*a*ifelse(b==3,1.5,1)

count <- 1:20
count[1:20] <- 1

data <-data.frame(cbind(y,a,b,count))
data$b <- factor(data$b)

set.seed(1)
x <- tweedie.profile(y ~ 1, offset=log(count),
                     do.plot=TRUE, do.smooth=FALSE, method="series",
                     data=data)

tweedie.p <- x$xi.max

# glm to predict y
glm_example <- glm(y ~ a+b,
            family=tweedie(var.power=tweedie.p, link.power=0),
            data=data, offset=log(count), 
            weights=count^(tweedie.p - 1))

summary(glm_example)

data$glm <- predict(glm_example,newdata=data,type="response")

glm_example_names <- names(glm_example$coefficients)
glm_example_coefs <- cbind(glm_example_names,exp(glm_example$coefficients),
                           glm_example$coefficients)
glm_example_coefs

# Model: y=2647.56*1.0000227^a*ifelse( b = 3, 0.06,1)
# desired model: y=0.2*a*ifelse(b=3,1.5,1) 
$\endgroup$
1
  • 3
    $\begingroup$ This appears to be a question requesting advice and education on statistical methods rather than on coding. Hence my vote to migrate (which appears on the SO interface as a close vote.). $\endgroup$
    – DWin
    Apr 21, 2016 at 19:04

1 Answer 1

1
$\begingroup$

I figured out the problem with the code. If I change the offset from offset(count) to offset(a) it works perfectly showing intercept = 0.2 and the coefficient for b = 3 is 1.5.

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy