r - Cumulatively apply function in dplyr -


consider following data:

df <- data.frame(names = sample(letters[1:5], 20, replace = t), numbers = 1:20) 

for have function cumsum, such each row in group, computes cumulative sum of numbers row

library(dplyr) df %>%   group_by(names) %>%   mutate(cumsum_numbers = cumsum(numbers)) 

i wish apply general function my_fn cumulatively in same manner cumsum. my_fn has general form:

my_fn <- function(vector){   # stuff  vector   return(x) # x numeric scalar  } 

that is, takes vector of previous values row, , returns scalar.

the following code not work:

df %>%   group_by(names) %>%   mutate(cumsum_numbers = my_fn(numbers)) # apply my_fn                              # each group in numbers, returning                              # same value each grouping level 

so guess want like:

df %>%   group_by(names) %>%   mutate(cumsum_numbers = cum_my_fn(numbers)) 

note example function mean calculating cumulative mean. interestingly dplyr has implemented cummean, don't know internal workings of can't work out how implement behaviour general function.


Comments

Popular posts from this blog

sequelize.js - Sequelize group by with association includes id -

android - Robolectric "INTERNET permission is required" -

java - Android raising EPERM (Operation not permitted) when attempting to send UDP packet after network connection -