October 16, 2024
The best kind of help out there comes when you can make your question both:
use the reprex package (which is in the tidyverse).
reprex()
?Step 1. Write some R code and copy it into the clipboard (command-c or ctrl-c).
Step 2. Type reprex()
into the Console.
Step 3. Look at the Viewer to the right. Copy the Viewer output into GitHub, Slack, an email, Stack Overflow, Posit Community, etc.
reprex()
example - 1st tryCode:
Output of reprex()
:
reprex()
example - 2nd tryCode:
Output of reprex()
:
reprex()
example - 3rd tryCode:
Output of reprex()
:
library(lubridate)
#>
#> Attaching package: 'lubridate'
#> The following objects are masked from 'package:base':
#>
#> date, intersect, setdiff, union
jan31 <- ymd("2021-01-31")
jan31 + months(0:11) + days(31)
#> [1] "2021-03-03" NA "2021-05-01" NA "2021-07-01"
#> [6] NA "2021-08-31" "2021-10-01" NA "2021-12-01"
#> [11] NA "2022-01-31"
generate a reprex in R to demonstrate how to reorder a factor variable
Good coding style is like correct punctuation: you can manage without it, butitsuremakesthingseasiertoread.1
All of the following examples are taken from the Tidyverse style guide.
There are only two hard things in Computer Science: cache invalidation and naming things.
– Phil Karlton
Variable and function names should use only lowercase letters, numbers, and _
. Use underscores (_
) (so called snake case) to separate words within a name.
Do not put spaces inside or outside parentheses for regular funtion calls.
Most infix operators (==
, +
, -
, <-
, etc.) should always be surrounded by spaces:
If a function call is too long to fit on a single line, use one line each for the function name, each argument, and the closing ). This makes the code easier to read and to change later.
If the arguments to a function don’t all fit on one line, put each argument on its own line and indent:
# Good
iris |>
summarise(
Sepal.Length = mean(Sepal.Length),
Sepal.Width = mean(Sepal.Width),
.by = Species
)
# Bad
iris |>
summarise(Sepal.Length = mean(Sepal.Length), Sepal.Width = mean(Sepal.Width), .by = Species)
# Also bad
summarise(
iris,
Sepal.Length = mean(Sepal.Length),
Sepal.Width = mean(Sepal.Width),
.by = Species
)
Sometimes it’s useful to include a short pipe as an argument to a function in a longer pipe. Carefully consider whether the code is more readable with a short inline pipe or if it’s better to move the code outside the pipe and give it an evocative name.
The point is that coding happens in community. Not only do you want your code to run well, but you want other people to be able to understand it and use it. The more that you and others use the same syntax, the better the communication will be.