Skip to content

Instantly share code, notes, and snippets.

@hadley
Last active Oct 28, 2022
Embed
What would you like to do?
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