OLS estimator question: using a subset versus using a dummy-interacted variables Suppose that we are interested in the following model:
$$y_i=\beta_1+\beta_2x_{i2}+\beta_3x_{i3}+u_i$$
Here, there is a dummy variable $d_i$.
I am wondering whether the following estimators are equivalent:
[OLS using only the observations with $d_i=1$] versus [OLS $d_iy_i$ on $d_i1,\;d_ix_{i2},\; d_ix_{i2}$]
That is, using the subset versus using the dummy-interacted variables.
When I run the both cases, the former yields a consistent estimator but the latter does not.
(even though the values of the dummy is random assignment)
the example R code is as follows:
x2 <- rnorm(100000, 2, 1)
x3 <- rnorm(100000, 1.5, 1)
x4 <- rbinom(100000, 1, 0.5)
y <- 1+2*x2+2*x3+rnorm(10000)
dt <- data.frame(y = y, x2 = x2, x3 = x3)
est <- lm(y~x2+x3, data= dt, subset = (x4 == 1))
summary(est)
nobs(est)

dt4 <- data.frame(y = y*x4, x2 = x2*x4, x3 = x3*x4, x4=x4)
est4 <- lm(y~x2+x3, data= dt4)
summary(est4)
nobs(est4)

Is there a way to do the same estimation without throwing away some of the data?
Why do they have different results?
Why the latter yields worse results despite the large number of observations?

The answer:
The two regression should be the same because
$$[\sum_{i:d_i=1} x_ix_i']^{-1}[\sum_{i:d_i=1}x_iy_i]$$
using only the subsample with $d_i=1$ is equivalent to
$$[\sum_{i=1}^N x_id_ix_i']^{-1}[\sum_{i=1}^Nx_id_iy_i]$$.
The reason for the different results from the R code above is that the lm function do not make the interaction in the "intercept term".
see the following code and results is the same
one <- rep(1, 1000)
x1 <- rnorm(1000)
x2 <- rnorm(1000)
d <- sample(c(1,0), 1000,replace = T)
u <- rnorm(1000)
y <- one+2*x1+x2+u

# using subsample
dt <- data.frame(y=y,x1=x1,x2=x2,d=d)
est1 <- lm(y~x1+x2, data=dt, subset = (d==1))

# using interaction
X <- d*cbind(one,x1,x2)

# results
est1$coefficients
solve(t(X)%*%X)%*%(t(X)%*%y)
> est1$coefficients
(Intercept)          x1          x2 
  1.0077684   2.0358979   0.9949592 
> solve(t(X)%*%X)%*%(t(X)%*%y)
         [,1]
one 0.9547948
x1  2.0125214
x2  0.9677016
````

