Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Function in tidyverse

Tags:

r

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)
like image 554
Edward Avatar asked Oct 26 '25 03:10

Edward


1 Answers

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
like image 89
Ronak Shah Avatar answered Oct 28 '25 19:10

Ronak Shah



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!