我正在尝试在函数中使用 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).
为什么这些结果不同?谢谢。