Coupla nit comments, then a Zen of R and alternative solution.
Nit 1. Add
library(dyplr)
to the MWE. See the FAQ: How to do a minimal reproducible example reprex
for beginners, because using a reprex
requires the libraries to be specifically called.
Nit2. Do not name objects df, data, D, c, t
or any other name of a function in namespace. Doing so will eventually result in a cannot subset closure error.
Zen. Every R
problem can be thought of with advantage as the interaction of three objects— an existing object, x , a desired object,y , and a function, f, that will return a value of y given x as an argument. In other words, school algebra— f(x) = y. Any of the objects can be composites.
In the sample code, DF
has the role of x and has the role of y. Both are objects of class
tibble
. They differ in that the latter omits one column and two rows. In the example, f is the composite function for ... %>% filter ... select .. bind_rows
.
It doesn't have to be that complicated, using the subset operator [
library(dplyr)
#>
#> Attaching package: 'dplyr'
#> The following objects are masked from 'package:stats':
#>
#> filter, lag
#> The following objects are masked from 'package:base':
#>
#> intersect, setdiff, setequal, union
xA <- c(1:5)
xB <- c(11:15)
xC <- c(21:25)
DF <- tibble(xA,xB,xC)
AllResults <- DF[2:4,1:2]
AllResults
#> # A tibble: 3 × 2
#> xA xB
#> <int> <int>
#> 1 2 12
#> 2 3 13
#> 3 4 14
The power of R
derives in large part from its presentation to the user as a functional programming language. Unfortunately, many users either come from to R
from a background in a procedural language with its do this, then do that, but if ... mindset or simply get lost in punctuation. Tidyease attempts to relieve the cognitive dissonance with a chaining, through %>% approach, rather than a nesting f(h(g(h(x))) syntax. This can be very helpful, but comes at the expense of a fair amount of overhead, as shown in this example.