Error in model.frame.default(object, data, xlev = xlev) : object is not a matrix

▼魔方 西西 提交于 2021-01-29 02:28:53

问题


3 days old to R and can't figure out what I'm doing wrong. I'm trying to send some columns with two way interactions into a glmnet cox model. I have some data.frame() called dtable

Edit to make the code reproducible

xs<-c("Col1", "Col2", "Col3")
v<-c(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, NA, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, NA, 25, 26, 27, 28, 29, 30)
df<-data.frame(matrix(v,ncol=3))
dm<-as.matrix(df)
dm<-matrix(dm[complete.cases(dm)], ncol=3)
colnames(dm)<-xs
dfdata<-data.frame(dm)
f<-as.formula(time~.*.)
xmatrix<-model.matrix(f, dfdata)[,-1]

When I run this I get the error

Error in model.frame.default(object, data, xlev = xlev) :    
object is not a matrix

Thanks in advance


回答1:


It's because of the formula: time~.*. In the data.frame() there is no time column for the formula to cross everything by.




回答2:


I suspect the error is telling exactly what is wrong. The object you are passing to model.matrix() is not a matrix. What is the result of class(data)? Probably a data.frame.

Try adding as.matrix() to the model.matrix() call to data.

Two other notes - don't call your data.frames data. Also asks questions here using a reproducible example. You'll get better responses.




回答3:


I think instead of this:

dm<-matrix(dm[complete.cases(dm)], ncol=3)

you want this:

dm <- as.matrix(dm[complete.cases(dm), ])

Not to toot my own horn (too much), but consider using glmnetUtils to simplify the task of managing data frames, formulas and model matrices.



来源:https://stackoverflow.com/questions/40682261/error-in-model-frame-defaultobject-data-xlev-xlev-object-is-not-a-matrix

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!