The “predict” Function in R

  • Package: base

  • Purpose: Generate predictions from a fitted model.

  • General class: Method

  • Required argument(s):

    • object: A fitted model object (e.g., from lm, glm, randomForest).

    • newdata: Data frame or matrix containing the new data for which predictions are to be made.

  • Notable optional arguments:

    • type: Type of prediction (e.g., “response” for the fitted values, “prob” for probabilities, depending on the model).

    • se.fit: Boolean indicating if standard errors for predictions should be returned (specific to some models).

  • Example:

  • # Load the required library
    library(MASS)

    # Example dataset
    data(Boston)

    # Fit a linear model
    model <- lm(medv ~ ., data = Boston)

    # New data for prediction
    new_data <- Boston[1:5, ]

    # Generate predictions
    predictions <- predict(model, newdata = new_data, type = "response")

    # Print predictions
    print(predictions)

  • In this example, the predict function is used to generate predictions from a linear model fitted to the Boston dataset. The newdata argument specifies the data for which predictions are to be made, and type = "response" indicates that we want the predicted values of the response variable. The function outputs the predictions for the specified new data.

Previous
Previous

The “neuralnet” Function in R

Next
Next

The “naive_bayes” Function in R