fs::dir_tree("_labs/lab02/R/")
## _labs/lab02/R/
## └── model-vetiver-r.qmdR processing layer
This chapter repeats the Lab 2 steps from model-vetiver.qmd in R. The source Quarto document can be found in _labs/lab02/R/model-vetiver-r.qmd.
Load packages
library(palmerpenguins)
library(plumber)
library(dplyr)
library(duckdb)
library(fastDummies)
library(vetiver)
library(pins)Get Data
We load the palmerpenguins data and create a connection with dbConnect(). Then we register the R data frame with duckdb and create the penguins table:
penguins_data <- palmerpenguins::penguins
con <- dbConnect(duckdb::duckdb(), "my-db.duckdb")
duckdb_register(con, "penguins_data", penguins_data)
dbExecute(con, "CREATE OR REPLACE TABLE penguins AS SELECT * FROM penguins_data")We then read the penguins table back with dbGetQuery(), drop missing rows with na.omit(), and disconnect from the database:
df <- dbGetQuery(con, "SELECT * FROM penguins") |>
na.omit()
dbDisconnect(con)We can confirm the data loaded by viewing the top rows of df:
head(df, 3) species island bill_length_mm bill_depth_mm flipper_length_mm body_mass_g
1 Adelie Torgersen 39.1 18.7 181 3750
2 Adelie Torgersen 39.5 17.4 186 3800
3 Adelie Torgersen 40.3 18.0 195 3250
sex year
1 male 2007
2 female 2007
3 female 2007Define Model and Fit
Next, we create dummy variables (one-hot encoding) for species and sex and fit a linear regression model that predicts body_mass_g:
X <- df |>
select(bill_length_mm, species, sex) |>
dummy_cols(
select_columns = c("species", "sex"),
remove_first_dummy = TRUE) |>
select(-species, -sex)
y <- df$body_mass_g
model <- lm(y ~ ., data = X)Extract model fit statistics
We pull the R-squared, intercept, coefficients, and column names from the fitted model:
r_squared <- summary(model)$r.squared
intercept <- coef(model)[1]
coefficients <- coef(model)[-1]
column_names <- names(X)Then we print each statistic to the console with cat():
cat("R^2:", r_squared, "\n")
cat("Intercept:", intercept, "\n")
cat("Columns:", paste(column_names, collapse = ", "), "\n")
cat("Coefficients:", paste(coefficients, collapse = ", "), "\n")The output should match the Python model in model-vetiver.qmd:
R^2: 0.8555369
Intercept: 2169.27
Columns: bill_length_mm, species_Chinstrap, species_Gentoo, sex_male
Coefficients: 32.5368867712031, -298.765534465279, 1094.86739144898, 547.36692407721Turn into Vetiver Model
vetiver_model() wraps the fitted lm() object into a deployable vetiver model named penguin_model:
v <- vetiver_model(model, model_name = "penguin_model")Save to Board
board_folder() creates a pins board in a local models/ folder, and vetiver_pin_write() writes v to it:
model_board <- board_folder("./models")
vetiver_pin_write(model_board, v)Below we can see the model information stored in the models/ folder:
fs::dir_tree("_labs/lab02/R/models/")
## _labs/lab02/R/models/
## └── penguin_model
## └── 20250923T141916Z-cca3d
## ├── data.txt
## └── penguin_model.rdsTurn model into API
Unlike Python, R needs a plumber router (the object that holds an API’s endpoints) from plumber::pr(). We pipe the router into vetiver_api() along with the deployable vetiver_model() object:
app <- pr() |>
vetiver_api(v)Recap
Getting the data into
duckdbfrom R takes one extra step:duckdb_register()exposes thepenguins_datadata frame to the connection beforeCREATE OR REPLACE TABLEbuilds the table.na.omit()then drops the missing rows (Python useddropna()).fastDummies::dummy_cols()withremove_first_dummy = TRUEreplacesget_dummies(drop_first = True), andlm()replacesLinearRegression(). The model information comes fromsummary(model)$r.squaredandcoef()instead of thescikit-learnattributes.vetiver_model(),board_folder(), andvetiver_pin_write()mirror the Python functions. The API step differs: R needs aplumberrouter fromplumber::pr()piped intovetiver_api(), while Python’sVetiverAPI()builds the API directly from the model.
Next, Lab 3: Databases and APIs builds Shiny apps in Python and R that send requests to these APIs.