Kapono
Kapono

Reputation: 1

Trying to predict values in a column using a model in R

I'll state up front that I have little experience in R, and really appreciate any help folks can provide.

I have a data frame (I think) of values:

enter image description here

I am trying to predict each value of the "PredBFwdth" column, using a model I've created from other data and the values of "ThatwgFAC" and "ThalwgSlop".

The name of the model is "Model"; it is a generalized additive model, so I would be using predict.gam. I thought the code would look something like:

PredBFwdth = predict.gam(Model, ThalwgFAC, ThalwgSlop)

This doesn't work, obviously. I'll need to make predictions for every row in the data, using corresponding values from the ThalwgFAC and ThalwgSlop columns and the model. Can someone assist? I've poked around looking for answers, but the code on other folks questions is indecipherable to me. :(

Upvotes: 0

Views: 1184

Answers (1)

MDEWITT
MDEWITT

Reputation: 2368

I strongly recommend giving enough data and code to create a reproducible example. That means a sample of what your data could look like and what code you are trying in order to facilitate help.

First I'll start with some fake data that is in a data.frame

dat <- data.frame(

ThalwgFAC = rnorm(100,3,5),
ThalwgSlop = rnorm(100,3,2),
ThalwgEv = rnorm(100,2,2)
)

Next, you fit your model

library(mgcv)

fit <- gam(ThalwgEv ~ s(ThalwgFAC) + s(ThalwgSlop), data = dat)

Now to your question about predicting new data, you can just feed the new data (as a data frame) to the predict function and specify which model you are going to use (the fit object from above). This presumes the data frame contains the same variable names that were used for the model (e.g. ThalwgFAC and ThalwgSlop).

dat2 <- data.frame(
  
  ThalwgFAC = rnorm(100,3,5),
  ThalwgSlop = rnorm(100,3,2),
  ThalwgEv = rnorm(100,2,2)
)

pred <- predict(fit, newdata = dat2)

The predict function will pick up the class of the fit object, so no need to specify the method to use (i.e. predict.gam).

Upvotes: 1

Related Questions