I tried to calculate the cumsum with a depreciation rate.
I have a grouped dataframe with a column number. I want to add the number one by one with depreciation. If the rate is 1, then the cumsum function in base r is good enough. But if not, let's say the rate of 0.5 (means each number will multiply by 0.5 to add the next number), cumsum is not enough. I tried to write my own function to work with dplyr, but it fails.
library(tidyverse)
# dataframe
id=sample(1:5,25,replace=TRUE)
num=rnorm(25)
df=data.frame(id,num)
# my custom function
depre=function(data){
rate=0.5
r=nrow(data)
sl=data$num
nl=data$num
for (i in 2:r){
sl[i]=sl[i-1]*rate+nl[i]
}
return(sl)
}
# work with one group
df %>% filter(id==1) %>% depre(.)
# failed to work with dplyr
df %>% group_by(id) %>% mutate(sl=depre(.))
I expect the first element of column s, should be the same as in column num. But the following ones, should be depreciate by times 0.5 and add next num. It works in one group, but failed in multi-grouped dataframe. The error message is: "Error: Column sl
must be length 6 (the group size) or one, not 25". I have no idea. Could anyone have a clue? Thanks
Your function would work if you pass vector to your function instead of dataframe
depre <- function(num){
rate = 0.5
r= length(num)
sl = num
nl = num
for (i in 2:r){
sl[i]=sl[i-1]*rate+nl[i]
}
return(sl)
}
and then apply it by group.
library(dplyr)
df %>% group_by(id) %>% mutate(sl = depre(num))
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments