The Design of Everyday R Functions
“All artificial things are designed.”
Make functionality obvious
🔋 Forgive “close enough” input
ℹ️ Help users fix mistakes
compile_sales_df(
items = c("item", "price", "", ""),
prices = c("paper towels", "12.33", "toilet paper", "20.77")
)Warning in compile_sales_df(items = c("item", "price", "", ""), prices =
c("paper towels", : NAs introduced by coercion
item price sales_tax total_price
1 item NA NA NA
2 price 12.33 1.02 13.35
3 NA NA NA
4 20.77 1.72 22.49
compile_sales_df(
items = c("item", "price", "", ""),
prices = c("paper towels", "12.33", "toilet paper", "20.77")
)Error in `compile_sales_df()`:
! `prices` <character> must be coercible to <double>
✖ Can't convert some values due to non-numeric strings.
• Locations: 1 and 3
• Values: "paper towels" and "toilet paper"
compile_sales_df <- function(items, prices, tax_rate = 0.0825) {
prices <- stbl::to_dbl(prices) |>
stbl::replace_stbl_error(
c(
"{.arg prices} must be numeric",
i = "Check that the input CSV is formatted correctly"
)
)
sales_tax <- ceiling(prices * tax_rate * 100) / 100
total_price <- prices + sales_tax
data.frame(
item = items,
price = prices,
sales_tax = sales_tax,
total_price = total_price
)
}compile_sales_df <- function(items, prices, tax_rate = 0.0825) {
prices <- stbl::to_dbl(prices) |>
stbl::replace_stbl_error(
c(
"{.arg prices} must be numeric",
i = "Check that the input CSV is formatted correctly"
),
subclass = c("incompatible_values")
)
sales_tax <- ceiling(prices * tax_rate * 100) / 100
total_price <- prices + sales_tax
data.frame(
item = items,
price = prices,
sales_tax = sales_tax,
total_price = total_price
)
}compile_sales_df <- function(items, prices, tax_rate = 0.0825) {
prices <- stbl::to_dbl(prices) |>
stbl::replace_stbl_error(
c(
"{.arg prices} must be numeric",
i = "Check that the input CSV is formatted correctly"
),
subclass = c("incompatible_values", "double")
)
sales_tax <- ceiling(prices * tax_rate * 100) / 100
total_price <- prices + sales_tax
data.frame(
item = items,
price = prices,
sales_tax = sales_tax,
total_price = total_price
)
}Error in `compile_sales_df()`:
! `prices` must be numeric
ℹ Check that the input CSV is formatted correctly
❗ Problem statement
ℹ️ Suggestions
❌ Exact issue (if known)
🔵 More info
Make functionality obvious
🔋 Forgive “close enough” input
ℹ️ Help users fix mistakes