library(rpart)
library(rpart.plot)
library(skimr)
airbnb = read.csv('https://ec242.netlify.app/data/airbnb_chicago.csv')Nonparametric Regression II
Our data and goal
We’ll use every Chicago Airbnb listing scraped by Inside Airbnb in September 2026 to build and tune a non-parametric model of nightly price using a regression tree (or decision tree, same thing). I’ve trimmed it to 18 columns and dropped the 1% of listings priced over $1,500.

Guess the price
Here are three real listings. Write down a nightly price for each one.
guess = airbnb[c(351, 7006, 1082), ]| listing | room_type | accommodates | bedrooms | bathrooms | minimum_nights | number_of_reviews | superhost | host_listings |
|---|---|---|---|---|---|---|---|---|
| A | Private room | 2 | 1 | 1 | 2 | 73 | 1 | 4 |
| B | Entire home/apt | 6 | 2 | 2 | 2 | 118 | 1 | 3 |
| C | Entire home/apt | 4 | 2 | 2 | 2 | 49 | 1 | 99 |
We’ve learned that our RMSE calculations have a hard time with NAs in the data. So let’s use the skim output to tell us which variables have too many NA (see n_missing) values and should be dropped. Let’s set a high bar here, and drop anything that isn’t 100% complete. Of course, there are other things we can do (impute the NAs, or make dummies for them), but for now, it’s easiest to drop them.
Remember, skim() is for your own exploration, it’s not something that you should include in your output.
skim(airbnb)The only two variables that aren’t 100% complete are review_scores_rating and reviews_per_month, so those are the ones we drop. We also drop listing_url. It is a web address, not a predictor.
airbnb_clean = airbnb %>%
dplyr::select(-review_scores_rating, -reviews_per_month, -listing_url)Once cleaned, we should be able to use rpart(price ~ ., data = airbnb_clean) and not have any NAs in our prediction. That’s what we’ll do in our first Breakout.
Predicting price
I’m going to have you form groups of 2-3 to work on live-coding. One person in the group will need to have Rstudio up, be able to share screen, and have the correct packages loaded (rpart and rpart.plot, plus dplyr and skimr). Copy the rmse and get_rmse code into a blank R script (you don’t have to use RMarkdown, just use a blank R script and run from there). You’ll also want to have these functions from last week loaded:
rmse = function(actual, predicted) {
sqrt(mean((actual - predicted) ^ 2))
}get_rmse = function(model, data, response) {
rmse(actual = subset(data, select = response, drop = TRUE),
predicted = predict(model, data))
}For the first breakout, all I want you to do is the following. We are trying to predict price for this exercise:
- Estimate a default regression tree on
airbnb_cleanusing the default parameters (use the whole dataset for now, we’ll train-test on the problem set). Call itonetree. - Use
rpart.plotto visualize your regression tree, and talk through the interpretation with each other. - Calculate the RMSE for your regression tree.
We’ll spend about 10-15 minutes on this. You may find something odd at first and may need to drop more variables…
10-15 minutes
Breakout #1 discussion
Let’s choose a group to share their plot and discuss the results. The odd thing you should have hit: quote_per_night is the nightly price from a booking quote, so the tree splits on it and nothing else. Drop it. Then look at estimated_revenue: what is it computed from? Drop that too (airbnb_clean$estimated_revenue = NULL), re-run, and we’ll keep using airbnb_clean for the rest of today.

- Who are the hosts with 89 or more listings, and why are they so expensive?
- Why would a private room with a one-night minimum cost more than one with a longer minimum?
Check your guesses
my_guess = c(150, 300, 400) # replace with your guesses for A, B, C
data.frame(listing = c("A", "B", "C"),
you = my_guess,
tree = predict(onetree, guess),
actual = guess$price)
rmse(guess$price, my_guess)
rmse(guess$price, predict(onetree, guess))What was the RMSE of your guesses? What was the RMSE of the tree?
Breakout #2: Find the deals
A deal is a listing with a price far below the tree’s prediction.
- Add the tree’s prediction to
airbnbas a new column,pred. - Make a new column,
deal = price - pred. - Keep the listings with at least 10 reviews. Sort them by
deal. - Open the
listing_urlfor the top five. Why are they cheap? - Why do the top deals all have the same prediction?
10-15 minutes
Breakout #3: Map the tree
Fit a tree on location only. Then predict a price for every point on a grid and plot it.
maptree = rpart(price ~ latitude + longitude, data = airbnb, cp = 0.005)
grid = expand.grid(longitude = seq(min(airbnb$longitude), max(airbnb$longitude), length.out = 300),
latitude = seq(min(airbnb$latitude), max(airbnb$latitude), length.out = 300))
grid$pred = predict(maptree, grid)
ggplot(grid, aes(x = longitude, y = latitude, fill = pred)) +
geom_raster() +
geom_point(data = airbnb, aes(x = longitude, y = latitude),
inherit.aes = FALSE, size = .1, alpha = .2) +
coord_quickmap() +
scale_fill_viridis_c(labels = scales::label_dollar())- Why are all the edges straight lines?
- What does the tree predict for a listing in Lake Michigan? Why?
- Change
cpto 0.002. What changes?
10-15 minutes
Side note: using lapply to repeat something
As we did in the last two labs, we’ll use lapply to iterate over a wide range of “tuning parameters” to optimize our model (find the lowest test RMSE).
Once we have a list of things we want to iterate on, lapply lets us do something to each element of the list, and then returns a list of results (of the same length as the input). The arguments of lapply are (1) the list we want to iterate over, (2) the function we want to use, and, when needed, (3) other arguments to pass to the function (that are the same for every element in the list). The list we want to iterate over might be a list of models (as we do when we want to use get_rmse on each model), or it might be a list (or a vector that can be coerced to a list) of tuning parameters.
Let’s say we wanted to repeat our TRY IT with the cp values of c(0, .01, .02, .03). We could make a list of those values, and use lapply to run rpart() and use each of the 4 values of cp. One way we could try doing this would be something like:
myList = lapply(c(0, .01, .02, .03), rpart, formula = price ~ ., data = airbnb_clean, cp = ???)The only problem here is that the first argument of rpart is not the cp parameter, so we can’t just pass it in additional arguments.
Instead, we previously introduced the anonymous function in lapply as follows:
myList = lapply(c(0, .01, .02, .03), function(x){
rpart(price ~ ., data = airbnb_clean, cp = x)
})Well, it gets us the right answer, but whaaaaaat is going on? Curly brackets? x?
This is an “anonymous function”, or a function created on the fly. Here’s how it works in lapply:
- The first argument is the list you want to do something to (same as before)
- The second argument would usually be the function you want to apply, like
get_rmse - Here, we’re going to ask R to temporarily create a function that takes one argument,
x. xis going to be each element of the vector you’re iterating over — here, each value ofcp. (myListis what comes out oflapply, not what goes in.)- Think of it as a loop:
- Take the first element of
c(0, .01, .02, .03)and refer to it asx. Run the function’s code. - Then it’ll take the second element and refer to it as
xand run the function’s code. - Repeat until every element has been used.
- Take the first element of
- Once the anonymous function has been applied to
x, the result is passed back and saved as the new element of the list output, always in the same position from where thexwas taken.
The curly brackets are the temporary function you want to create.
So you can think of it like this:
x = 0
myList[[1]] = rpart(price ~ ., data = airbnb_clean, cp = x)
x = 0.01
myList[[2]] = rpart(price ~ ., data = airbnb_clean, cp = x)
x = 0.02
myList[[3]] = rpart(price ~ ., data = airbnb_clean, cp = x)
As long as every entry in the vector you iterate over is a valid value of cp, then you’ll get the results in a list — here, a list of four fitted trees, not a list of cp values. When the list holds single numbers instead of models, unlist coerces it to a vector. This is also the same way we get the RMSE, but instead of the anonymous function, we write one out and use that.
If you had a list of rpart objects and wanted to, say, extract the cp tuning parameter from each, you could also use an anonymous function. Each rpart object has a list called control that includes all of the control (tuning) parameters used in its estimation:
cpList = lapply(myList, function(y){
y$control$cp
})
unlist(cpList)Here is lapply at work. Each panel is the location tree from Breakout #3 at a different value of cp.

Breakout #4
Using the loop method or the lapply method, generate 10 regression trees to explain price in airbnb_clean. You can iterate through values of cp, the complexity parameter, or minsplit, the minimum # of points a node has to have before rpart will even try to split it. If you vary minsplit, also set cp = 0, or the default cp will stop every tree at the same size.
10 minutes
Breakout #4 discussion
We’ll ask someone to share (a few of) their group’s 10 regression trees using rpart.plot. Use our website zoom link to share.
Breakout #5 (if time)
Use lapply to get a list of your RMSE’s (one for each of your models). The anonymous function may come in handy here (though it’s not necessary). Note that we are not yet splitting into test and train (which you will need to do on your lab assignment). That matters for what the plot looks like: because these are RMSEs on the same data we fit, they’ll keep falling as the trees get bigger (as cp goes to zero, or as minsplit shrinks), so there’s no bottom of the U to find here. The U only shows up once the RMSE is calculated on data the tree hasn’t seen.
Once you have your list, create the plot of RMSEs similar to the one we made in last week’s lab. Note: you can use unlist(myRMSE) to get a numeric vector of the RMSE’s (as long as all of the elements in myRMSE are numeric). Then, it’s a matter of plotting either with base plot or with ggplot (if you use ggplot you’ll have to put the RMSEs in a data frame first, with a second column holding the cp or minsplit value that goes on the x-axis).