1

I have a dataframe dfab that contains 2 columns that I used as argument to generate a series of linear models as following:

models = list()
for (i in 1:10){
    models[[i]] = lm(fc_ab10 ~ (poly(nUs_ab, i)), data = dfab)
}

dfab has 32 observations and I want to predict fc_ab10 for only 1 value.

I thought of doing so:

newdf = data.frame(newdf = nUs_ab)
newdf[] = 0
newdf[1,1] = 56
prediction = predict(models[[1]], newdata = newdf)

First I tried writing newdf as a dataframe with only one position, but since there are 32 in the dataset on which the model was built, I thought I had to provide at least 32 points as well. I don't think this is necessary though.

Every time I run that piece of code I am given the following error:

Error: variable 'poly(nUs_ab, i) was fitted with type “nmatrix.1” but type “numeric” was supplied. In addition: Warning message: In Z/rep(sqrt(norm2[-1L]), each = length(x)) : longer object length is not a multiple of shorter object length

I thought all I need to use predict was a LM model, predictors (the number 56) given in a column-named dataframe. Obviously, I am mistaken.

How can I fix this issue?

Thanks.

Jxson99
  • 347
  • 2
  • 16
  • 2
    It would be easier to help you if you provided a [reproducible example](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) with sample input data so we can run and verify the problem and test a possible solution. – MrFlick Sep 01 '17 at 19:12

1 Answers1

2

newdf should be a data.frame with column name nUs_ab, otherwise R won't be able to know which column to operate upon (i.e., generate the prediction design matrix). So the following code should work

newdf = data.frame(nUs_ab = 56)
prediction = predict(models[[1]], newdata = newdf)
platypus
  • 516
  • 3
  • 8
  • Thanks, playtpus. I keep facing the same error with this solution you proposed. I'll look closer into it and should I reach a solution, I'll select your answer accepted. – Jxson99 Sep 02 '17 at 16:04