There is dataframe raw_df
as below:
library(tidyverse)
detail <- data.frame(cat=c("a","a","a","b","b","b","b","c","c"),
single_amount=c(1,3,7,2,1,4,6,1,6))
total <- data.frame(cat=c("a","b","c"),
total_amount=c(20,10,9))
raw_df <- detail %>% left_join(total,by='cat')
I defined self function allocate_data_m
to allocate total_amount
when cumsum(single_data)
is less then total_amount
allocate_data_m <- function(data,single_data,total_data){
out <- cumsum_single_data <- rep('NA',nrow(data))
for (grouprow in seq_len(nrow(data))){
cumsum_single_data[grouprow] <-
if_else(grouprow ==1,data[grouprow,single_data],
cumsum_single_data[grouprow-1] + data[grouprow,single_data])
out[grouprow] <- if_else(cumsum_single_data[grouprow] < data[grouprow,total_data],data[grouprow,single_data],0)
}
out
}
when run the allocate_data_m
in mutate
, the error occur .Anyone can help ? Thanks!
raw_df %>% group_by(cat) %>%
mutate(amount_x_all = allocate_data_m(cur_data(),single_amount,total_amount))