Quantcast
Channel: Active questions tagged r - Stack Overflow
Viewing all articles
Browse latest Browse all 205466

Referencing variable created within itself in case_when statement

$
0
0

I am creating a variable that should grow the previous observation of the variable at a specified growth rate. I am doing this with a case_when statement in R. This is my code so far:

consolidated_balances_comp %>%  mutate(
  fee = 0.05/12,
  class_start = case_when(
   date == "2011-01-31"& lead(fund_name,1) == fund_name ~ balances * (1+lead(returns, 1))/2,
   TRUE ~ 0
  ),
  benchmark_compare_1 = case_when(
    date == "2011-02-28"& lag(fund_name,1) == fund_name & date_added =="2011-01-31" ~ (lag(class_start,1) + in_and_out)*(1+ returns_bench1 - fee)^0.25,
    date_added >= "2011-02-28"& lead(fund_name,1) == fund_name & lag(date,1) == date_added ~  (lag(balances,1) * (1+ returns_bench1 -fee)^0.5 + in_and_out) *(1+ returns_bench1 - fee)^0.5,
    TRUE ~ 0
  ),
  damages_benchmark_1 = case_when(
    lag(date,2) == date_added & lag(fund_name,1) == fund_name  ~     
      (lag(benchmark_compare_1,1) * (1+returns_bench1 - fee)^0.5 +in_and_out )*(1+returns_bench1 - fee)^0.5,
    lag(date,2) > date_added & lag(fund_name,1) == fund_name ~
      (damages_benchmark_1[-1] * (1+returns_bench1 - fee)^0.5 +in_and_out )*(1+returns_bench1 - fee)^0.5
  )

It is this last part of the code (the variable "damages_benchmark_1") that is giving me trouble as I am referencing the variable created within itself.


Viewing all articles
Browse latest Browse all 205466

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>