Open main menu
Home
Random
Recent changes
Special pages
Community portal
Preferences
About Wikipedia
Disclaimers
Incubator escapee wiki
Search
User menu
Talk
Dark mode
Contributions
Create account
Log in
Editing
R (programming language)
(section)
Warning:
You are not logged in. Your IP address will be publicly visible if you make any edits. If you
log in
or
create an account
, your edits will be attributed to your username, along with other benefits.
Anti-spam check. Do
not
fill this in!
=== Native pipe operator === In R version 4.1.0, a native [[Pipeline (computing)|pipe operator]], <code>|></code>, was introduced.<ref>{{Cite web |title=R: R News |url=https://cran.r-project.org/doc/manuals/r-devel/NEWS.html |access-date=2024-03-14 |website=cran.r-project.org}}</ref> This operator allows users to chain functions together one after another, instead of a nested function call. <syntaxhighlight lang="rout"> > nrow(subset(mtcars, cyl == 4)) # Nested without the pipe character [1] 11 > mtcars |> subset(cyl == 4) |> nrow() # Using the pipe character [1] 11 </syntaxhighlight> Another alternative to nested functions, in contrast to using the pipe character, is using intermediate objects: <syntaxhighlight lang="rout"> > mtcars_subset_rows <- subset(mtcars, cyl == 4) > num_mtcars_subset <- nrow(mtcars_subset_rows) > print(num_mtcars_subset) [1] 11 </syntaxhighlight>While the pipe operator can produce code that is easier to read, it has been advised to pipe together at most 10 to 15 lines and chunk code into [[Task (project management)|sub-tasks]] which are saved into objects with meaningful names.<ref>{{Cite book |last=Wickham |first=Hadley |url=https://r4ds.hadley.nz/ |title=R for data science: import, tidy, transform, visualize, and model data |last2=Çetinkaya-Rundel |first2=Mine |last3=Grolemund |first3=Garrett |date=2023 |publisher=O'Reilly |isbn=978-1-4920-9740-2 |edition=2nd |location=Beijing; Sebastopol, CA |chapter=4 Workflow: code style |oclc=on1390607935 |chapter-url=https://r4ds.hadley.nz/workflow-style.html}}</ref> Here is an example with fewer than 10 lines that some readers may still struggle to grasp without intermediate named steps:<syntaxhighlight lang="r" line="1">(\(x, n = 42, key = c(letters, LETTERS, " ", ":", ")")) strsplit(x, "")[[1]] |> (Vectorize(\(chr) which(chr == key) - 1))() |> (`+`)(n) |> (`%%`)(length(key)) |> (\(i) key[i + 1])() |> paste(collapse = "") )("duvFkvFksnvEyLkHAErnqnoyr")</syntaxhighlight>
Edit summary
(Briefly describe your changes)
By publishing changes, you agree to the
Terms of Use
, and you irrevocably agree to release your contribution under the
CC BY-SA 4.0 License
and the
GFDL
. You agree that a hyperlink or URL is sufficient attribution under the Creative Commons license.
Cancel
Editing help
(opens in new window)