我试图在一个函数中使用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).为什么这些结果不同?谢谢。
发布于 2015-06-05 06:24:47
首先,您正在“倒退”(因为缺少一个更好的术语) 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 2https://stackoverflow.com/questions/30659465
复制相似问题