Week 13 · Advanced Statistical Programming using R
What is the fastest way to make an existing ggplot2 figure explorable in the browser?
ggplotly()gt tableAnswer: 3) ggplotly(p) turns a static ggplot2 object into an interactive plotly chart. Hover, zoom, and legend toggles come along for free.
What is an sf object in R?
geometry columnAnswer: 4) sf (Simple Features) objects behave like normal data frames. The geometry column stores the shape, and you can pipe through dplyr as usual.
Which language design contrast is correct?
NA, Python has NoneAnswer: 2) R was designed by statisticians for statistics. Python is general-purpose, and its data science tools live in libraries like pandas, numpy, and scikit-learn.
You write x[1] in Python and get the second element of the list. Why?
x[1] means “second-to-last” in Pythonx[0] is the first elementAnswer: 4) Python counts from 0. Slices like x[1:3] also exclude the end index. Both differ from R and are classic beginner traps.
Which Python code correctly defines a function that returns the sum of two numbers?
function add(a, b) { return a + b }def add(a, b): return a + badd <- function(a, b) a + badd = (a, b) => a + bAnswer: 2) Python uses def, a colon, and an indented body. Unlike R, the last expression is not returned automatically, so return is mandatory.
Which R container is closest to a Python dictionary ({"anna": 31, "ben": 25})?
data.framematrixlist(anna = 31, ben = 25)c(31, 25)Answer: 3) A named list stores key-value pairs like a dict. Tuples in Python have no direct R equivalent; sets map roughly to unique().
What does the {reticulate} package do?
Answer: 1) reticulate embeds Python in your R session. R and Python objects are translated on the fly, so a data frame becomes a pandas DataFrame and back.
In a Quarto document that uses {reticulate}, how do you read the R object penguins from a Python chunk?
import(penguins)py$penguinsread.csv("penguins.csv")r.penguinsAnswer: 4) Inside Python, r.penguins fetches the R object. The reverse works with py$x inside R to reach a Python variable.
You call numpy::linspace(0, 1, num = 5) from R via reticulate and get an error. What is the most likely fix?
num = 5L so R sends an integer instead of a doubletry()Answer: 3) Many Python functions expect integers. R numbers are doubles by default, so use the L suffix (5L) to send an integer across the border.
Your project needs a random-forest classifier from scikit-learn but you want to keep wrangling and plotting in R. What is the recommended workflow?
reticulate, plot back in RAnswer: 2) Let each language do what it does best. reticulate moves data across the border without file exports, so R handles wrangling and plots while Python handles the model.