R 中函数使用 model.matrix 的不同结果

Different outcome using model.matrix for a function in R

我正在尝试在函数中使用 model.matrix(我不会显示所有函数,只显示感兴趣的部分)但我注意到 model.matrix 的结果是不同的命令在函数内部使用。这是代码:

df <- data.frame(a=1:4, b=5:8, c= 9:12)

model.matrix(a~.,data=df)
#The outcome is:
(Intercept) b  c
1           1 5  9
2           1 6 10
3           1 7 11
4           1 8 12
attr(,"assign")
[1] 0 1 2
#Using model.matrix inside in a function
#Entries for function are a dataframe and a dependent var.
fun1 <- function(DF,vdep){
model.matrix(vdep ~.,data=DF)
}

fun1(df,df$a)
  (Intercept) a b  c
1           1 1 5  9
2           1 2 6 10
3           1 3 7 11
4           1 4 8 12
attr(,"assign")
[1] 0 1 2 3    
#As you can see the outcome includes dependent var (a).

为什么这些结果不同?谢谢

首先,您"regressing"(没有更好的术语)a反对其他一切。在函数内部,您正在对其他所有内容进行回归 vdep,包括 a。您的功能本质上只是在做 model.matrix(1:4 ~.,data=df)。公式参数是 "string",无法识别您看到的变量。

您可以按如下方式修改您的函数

fun2 <- function(DF,vdep){
  model.matrix(as.formula(paste(vdep, "~ .")), data = DF)
}  

fun2(df, "a")

  (Intercept) b  c
1           1 5  9
2           1 6 10
3           1 7 11
4           1 8 12
attr(,"assign")
[1] 0 1 2