我正在尝试在函数中使用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).
为什么这些结果不同?谢谢。
首先,您正在“退缩”(因为没有更好的用语)而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
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句