Edward
Edward

Reputation: 4623

Function in tidyverse

I want to create tidyverse with intermediate function. I have a structure as

temp1 = sapply(df, function(x) .....)
temp2 = sapply(temp1, function(x) .......... )
temp3 = sapply(df, function(x) ..........)
temp = data.frame(temp2/temp3)

And I want to get something like this

sapply(df, function(x) .......) %>% sapply(df, function(x) ....... )
 %>% ......

Reproducible example:

df = data.frame(a = c(1,2,3), b = c(1,2,3))
temp1 = sapply(df, function(x) x*3)
temp2 = sapply(temp1, function(x) x+4 )
temp3 = sapply(df, function(x) x/4)
temp = data.frame(temp2/temp3)

Upvotes: 4

Views: 240

Answers (3)

WeiQiang
WeiQiang

Reputation: 1

You can use brackets to wrap a whole pipe chain and use it as a data frame.

(df %>% sapply(., function(x) x*3) %>% sapply(., function(x) x+4 )) / 
  (df %>% sapply(., function(x) x/4) )

Upvotes: 0

Ronak Shah
Ronak Shah

Reputation: 388797

Assuming you have more complicated functions to perform on every column than the one shown you could use purrr functions like :

library(purrr)

map2_df(map(df, ~.x * 3 + 4), map(df, ~.x/4), `/`)

#    a     b
#  <dbl> <dbl>
#1  28    28  
#2  20    20  
#3  17.3  17.3

Upvotes: 1

Dan Chaltiel
Dan Chaltiel

Reputation: 8484

To the best of my knowledge, the pipe operator do not remember the first block of the chain, only the previous one, so you have to use an intermediate step.

However, you can simplify the first part of your code to a pipeline:

temp1 = df %>% sapply(function(x) x*3) %>% sapply(function(x) x+4)
temp = temp1/sapply(df, function(x) x/4)

Upvotes: 1

Related Questions