Skip to content

Instantly share code, notes, and snippets.

@hadley
Last active January 21, 2024 03:22
Show Gist options
  • Save hadley/1986a273e384fb2d4d752c18ed71bedf to your computer and use it in GitHub Desktop.
Save hadley/1986a273e384fb2d4d752c18ed71bedf to your computer and use it in GitHub Desktop.
data(diamonds, package = "ggplot2")
# Most straightforward
diamonds$ppc <- diamonds$price / diamonds$carat
# Avoid repeating diamonds
diamonds$ppc <- with(diamonds, price / carat)
# The inspiration for dplyr's mutate
diamonds <- transform(diamonds, ppc = price / carat)
diamonds <- diamonds |> transform(ppc = price / carat)
# Similar to transform(), but uses assignment rather argument matching
# (can also use = here, since = is equivalent to <- outside of a function call)
diamonds <- within(diamonds, {
ppc <- price / carat
})
diamonds <- diamonds |> within({
ppc <- price / carat
})
# Protect against partial matching
diamonds$ppc <- diamonds[["price"]] / diamonds[["carat"]]
diamonds$ppc <- diamonds[, "price"] / diamonds[, "carat"]
# FORBIDDEN
attach(diamonds)
diamonds$ppc <- price / carat
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment