r - Split-apply-combine with function that returns multiple variables -


i need apply myfun subsets of dataframe , include results new columns in dataframe returned. in old days, used ddply. in dplyr, believe summarise used that, this:

myfun<- function(x,y) {   df<- data.frame( a= mean(x)*mean(y), b= mean(x)-mean(y) )              return (df) }  mtcars %>%   group_by(cyl) %>%   summarise(a = myfun(cyl,disp)$a, b = myfun(cyl,disp)$b) 

the above code works, myfun i'll using computationally expensive, want called only once rather separately a , b columns. there way in dplyr?

since function returns data frame, can call function within group_by %>% do applies function each individual group , rbind returned data frame together:

mtcars %>% group_by(cyl) %>% do(myfun(.$cyl, .$disp))  # tibble: 3 x 3 # groups:   cyl [3] #    cyl                 b #  <dbl>     <dbl>     <dbl> #1     4  420.5455 -101.1364 #2     6 1099.8857 -177.3143 #3     8 2824.8000 -345.1000 

Comments

Popular posts from this blog

ubuntu - PHP script to find files of certain extensions in a directory, returns populated array when run in browser, but empty array when run from terminal -

php - How can i create a user dashboard -

javascript - How to detect toggling of the fullscreen-toolbar in jQuery Mobile? -