简体   繁体   中英

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)

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)

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

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) )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM