2

我正在尝试在函数中使用 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).

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

4

1 回答 1

2

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

您可以修改您的功能如下

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
于 2015-06-05T06:24:47.687 回答