A conceptual solution for this scenario has been posted in:
How do you deal with "nested" variables in a regression model?
Problem is I am having trouble using this solution in R - glm() or lm().
I am using the model:
y ~ x1 + x1:x2
Unfortunately if I encode the unmeaninful/missing data as NA the default na.action removes the rows with NAs and leaves x1 with only one level - making the model equivalent to just:
y ~ x2
If I use argument to glm:
na.action = na.pass
I get an error:
Error in glm.fit(x = c(1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, : NA/NaN/Inf in 'x'
If instead I encode the missing variable as 0, the nested model:
y ~ x1 + x1:x2
Gives the exact same output as the non nested model:
y ~ x1 + x2
Here is my short script exploring this:
y = rnorm(100, 100, 10)
x1 = sample(c(0, 1), 100, rep=T)
x2 = sample(100:200, 100, rep=T)
x2[x1 == 0] = NA # when x1 is 0 x2 is NA
df = data.frame(y, x1, x2)
nest_NA = glm(y ~ x1 + x1:x2, data=df) # NAs removed
add_NA = glm(y ~ x1 + x2,, data=df)
nest_NA = glm(y ~ x1 + x1:x2, data=df, na.action = na.pass) # NAs allowed = error
add_NA = glm(y ~ x1 + x2,, data=df, na.action = na.pass)
x2[x1 == 0] = 0 # when x1 is 0 x2 is also 0
df = data.frame(y, x1, x2)
nest_zero = glm(y ~ x1 + x1:x2, data=df)
add_zero = glm(y ~ x1 + x2, data=df)
Am I missing something here?