how to solve predict.lm() error: variable 'affinity' was fitted with type “nmatrix.1” but type “numeric” was supplied

流过昼夜 提交于 2019-12-04 04:45:40

问题


I have a simple linear model:

mylm = lm(formula = prodRate~affinity, mydf)

where mydf is a dataframe which looks like:

 prodRate    affinity

1  2643.5744 0.005164040

2  2347.6923 0.004439970

3  1783.6819 0.003322830

when I use predict.lm() an error came up:

my_pred= predict(mylm,newdata=data.frame(affinity=seq(0,1,0.1)) )

Error: variable 'affinity' was fitted with type "nmatrix.1" but type "numeric" was supplied.

Why is that? how to fix it? Thanks!


回答1:


Thanks to the discussion with user20650 (see above), the bug was identified:

The mydf in mylm = lm(formula = prodRate~affinity, mydf) was created by adding an matrix-like column to the existed dataframe mydf as following:

mydf$affinity = matrix(somenumber)

i.e. the "affinity" column in mydf is made from a matrix and its structure remains as matrix. This matrix structure is NOT consistent with the "affinity" column in newdata=data.frame(affinity=seq(0,1,0.1)) in predict(mylm,newdata=...), which is a numeric vector.

solution1: fix mydf as following mydf <- data.frame(prodRate , affinity). i.e. make sure that the affinity column of mydf has a vector-like structure

solution2: keep the original mydf but enforce mydf$affinity as vector in the fomular: mylm <- lm(formula = prodRate ~ as.vector(affinity), mydf) so that the independent variable "affinity" in the linear model "mylm" has the vector-like structure instead of matrix-like structure, which will be consistent with the newdata=data.frame(affinity=seq(0,1,0.1)) in predict(mylm,newdata=...), which is a numeric vector.



来源:https://stackoverflow.com/questions/22337495/how-to-solve-predict-lm-error-variable-affinity-was-fitted-with-type-nmatr

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