how to predict() in r

To make predictions using a trained model in R, we use the predict() function. The predict() function takes two arguments: the trained model, and the new data for which we want to make predictions.

Here's an example of how to use predict() with a linear regression model:

main.r
# Fit a linear regression model on the mtcars data
model <- lm(mpg ~ wt + hp, data = mtcars)

# Create new data for which to make predictions
new_data <- data.frame(wt = c(2.5, 3.0), hp = c(150, 200))

# Use predict() to make predictions on the new data
predictions <- predict(model, newdata = new_data)

# View the predicted values
predictions
345 chars
12 lines

In this example, we fit a linear regression model on the mtcars dataset using two predictor variables: weight (wt) and horsepower (hp). We then create new data with two values for weight and horsepower, and use the predict() function to make predictions on the new data. The predicted values are stored in the predictions variable.

Note that the newdata argument in the predict() function must be in the same format (e.g., column names, data types) as the original data used to train the model.

gistlibby LogSnag