Last active
January 21, 2024 03:22
-
-
Save hadley/1986a273e384fb2d4d752c18ed71bedf to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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