Faller
Faller

Reputation: 1708

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

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

Upvotes: 4

Views: 32348

Answers (3)

Faller
Faller

Reputation: 1708

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

Upvotes: 5

Hong Ooi
Hong Ooi

Reputation: 57696

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.

Upvotes: 0

boshek
boshek

Reputation: 4416

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.

Upvotes: -2

Related Questions