Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a vector between pipes as intermediate step?

Tags:

r

dplyr

Within a piping chain, I am trying to store the variable names of the current data frame/tibble, and then continue.

In the example below, how do we get dplyr::filter() to receive the iris object? tmp should be used further down the chain. This attempt fails:

library(dplyr) 
iris %>% 
  {names(select(., where(is.numeric))) ->> tmp} %>%
  filter(., Species=="setosa")
like image 599
user167591 Avatar asked Dec 10 '25 23:12

user167591


2 Answers

You can just slightly modify your existing code by adding a ...; .} at the end of the intermediate line:

iris %>% 
  {names(select(., where(is.numeric))) ->> tmp; .} %>%
  filter(., Species=="setosa")

Though it may be more efficient to define it out of the pipe (i.e. tmp <- names(select(iris, where(is.numeric))).

like image 175
jpsmith Avatar answered Dec 13 '25 15:12

jpsmith


If the only reason to create tmp is to use it later in the pipeline then, in general, it is preferable to keep everything local within the pipeline rather than use a global variable. We can do that by assigning tmp locally rather than globally and then, along with the definition of tmp, placing the entire remainder of the pipeline within the {...} .

library(dplyr) 

iris %>% 
  { tmp <- names(select(., where(is.numeric)))
    filter(., Species=="setosa") %>%
    select(-Species) %>% 
    matplot(main = toString(tmp))
  }

(continued after graph) screenshot

Of course we could alternately break this up into two pipelines:

tmp <- iris %>%
  select(where(is.numeric)) %>%
  names

iris %>%
  filter(Species=="setosa") %>%
  select(-Species) %>% 
  matplot(main = toString(tmp))
like image 28
G. Grothendieck Avatar answered Dec 13 '25 15:12

G. Grothendieck



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!