Мои данные представляют собой серию из двух показателей, то есть процентных изменений. Я хочу рассчитать совокупный продукт для каждого, но обнулять этот совокупный продукт на 1 каждый раз, когда продукт для ставки A равен <= продукт для ставки B. </p>
В настоящее время я использую цикл for, который работаетхорошо. Я хотел бы получить решение, использующее purrr
, но функция accumulate
ограничена максимум 3 аргументами для функции накопления, и мне нужно 4.
Оцените любые предложения, MRE ниже.
library(tidyverse)
set.seed(20191008)
#create our data
df <- tibble(time = 1:100,
#A and B represent two rates, i.e. percentage change
A = runif(100) + 0.5,
B = runif(100) + 0.5,
#initialize the value of the cumulative products as 1
CumeProdA = 1,
CumeProdB = 1)
#Current solution uses a loop, but it's slow with large data
for(i in 2:nrow(df)){
#If the cumulative product of A <= that of B, then reset it to 1.
#Otherwise, continue accumulating
df$CumeProdA[i] <- ifelse(df$CumeProdA[i - 1] * df$A[i] <= df$CumeProdB[i - 1] * df$B[i],
1,
df$CumeProdA[i - 1] * df$A[i])
#Ditto with B
df$CumeProdB[i] <- ifelse(df$CumeProdA[i - 1] * df$A[i] <= df$CumeProdB[i - 1] * df$B[i],
1,
df$CumeProdB[i - 1] * df$B[i])
}
#I've done similar recursive calculations using purrr::accumulate,
#but it has a limit to how many arguments you can use in a function
df %>%
mutate(Example = accumulate(A, ~ ifelse(.x * .y < 1, 1, .x * .y)))
#The ultimate goal is to find the greatest difference in the cumulative products.
#If there's a shortcut to get to here, I'll take it!
df %>%
summarise(min(CumeProdB - CumeProdA))