Dplyr: how to get the last observation of a vector in a (very) compressed form?

Consider the following example.

return <- c(0.02,0.0,0.01,-0.04)
date <- c(1,2,3,4)
df_day <- data.frame(date,return)

> df_day
  date return
1    1   0.02
2    2   0.00
3    3   0.01
4    4  -0.04

I want to combine the returned data and get the composite results at time 4. A lengthy working solution is the following

df_agg1 <- df_day %>%
  arrange(date) %>%
  mutate(cumret = cumprod(1 + return) - 1,
         compound = last(cumret)) %>%
  filter(row_number() == 1)

> df_agg1
  date return cumret  compound
1    1   0.02   0.02 -0.011008

I do not understand why the above code cannot be shortened as follows:

df_agg2 <- df_day %>%
  arrange(date) %>%
  summarise(compound= last(cumprod(1 + return) - 1))

Here, my code should return a single value. Indeed, I get the last value (therefore, at time 4) of the vector of total products (minus one).

Sorry, I get

Error in eval (substitute (expr), envir, enc): Unsupported vector language type

What is the problem? Thank!

+4
source share

Source: https://habr.com/ru/post/1658690/


All Articles