R (programming language): Difference between revisions

Content deleted Content added
Klmr (talk | contribs)
Native pipe operator: This is an encyclopedia, not your personal blog.
Undid revision 1306189165 by Klmr (talk) There's some value to expand on what the pipe operator does, but the wording could be better
Tags: Undo Mobile edit Mobile app edit Android app edit App undo
Line 317:
> mtcars |> subset(cyl == 4) |> nrow() # Using the pipe character
[1] 11
</syntaxhighlight>
 
Another alternative to nested functions is the use of intermediate objects, rather than the pipe operator:
 
<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 is advisable to chain together at most 10-15 lines of code using this operator, as well as to chunk code into [[Task (project management)|sub-tasks]] that are saved into objects having 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>
 
The following is an example having fewer than 10 lines, which some readers may find difficult to grasp in the absence of 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>The following is a version of the preceding code that is easier to read:<syntaxhighlight lang="r">
default_key <- c(letters, LETTERS, " ", ":", ")")
 
f <- function(x, n = 42, key = default_key) {
split_input <- strsplit(x, "")[[1]]
results <- (Vectorize(\(chr) which(chr == key) - 1))(split_input) |>
(`+`)(n) |>
(`%%`)(length(key)) |>
(\(i) key[i + 1])()
combined_results <- paste(results, collapse = "")
return(combined_results)
}
 
f("duvFkvFksnvEyLkHAErnqnoyr")
</syntaxhighlight>