我有一个关于如何使用 predict()函数的问题。
我有一个包含n行和10列的数据集。第一列是因变量,其他变量是独立的。我在第一个变量上有50%的缺失数据,即x1,其他变量被完全观察到。我想通过使用相应案例和以下模型的回归系数来预测x1(缺失部分):
lm(new_A[,1]~new_A[,2]+new_A[,3]+new_A[,4]+new_A[,5]+new_A[,6]+new_A[,7]+new_A[,8]+new_A[,9]+new_A[,10]).
这是我的代码:
set.seed(40)
n=10000 # number of observation
m=10 # number of variables
mis=50 # percentage of missing data on the dependent variable
# I randomly assign 50% of missing data on the first variable (the dependent one in my future model)
for (i in 1:m){
X[,i]=runif(n,0,1)
}
X=data.frame(X)
# I randomly assign 50% of missing data on the first variable (the dependent one in my future model)
aa=runif(n,0,1)
X_MCAR[which(aa<=sort(aa)[mis*(n/100)]),1]=NA
# First, I create 2 datasets. One for the group A (x1,obs, x2|x1,obs, x3|x1,obs, ..., xm|x1,obs) --> new_A
# and one for group B (x1,mis, x2|x1,mis, x3|x1,mis, ..., xm|x1,mis) --> new_B
new_A=data.frame(X_MCAR[is.na(X_MCAR[,1])==FALSE,])
new_B=data.frame(X_MCAR[is.na(X_MCAR[,1])==TRUE,])
# Second, I stock the result of the regression on the group A in reg_A.
reg_A=lm(new_A[,1]~new_A[,2]+new_A[,3]+new_A[,4]+new_A[,5]+new_A[,6]+new_A[,7]+new_A[,8]+new_A[,9]+new_A[,10])
# Third, I predict x1,obs and x1,mis by using the regression coefficient from A.
x1_obs_hat=predict(reg_A, new_A)
x1_mis_hat=predict(reg_A, new_B)
它们应该是不同的,但实际上它们完全相同。谁能帮助我并说出代码中出了什么问题?因为x1_obs_hat和x1_mis_hat应该不同,因为我对B组使用不同的观察结果。
谢谢:)