R语言 使用tidy计算依赖于t-1中的值的值

ryoqjall  于 2022-12-05  发布在  其他
关注(0)|答案(1)|浏览(138)

我有一个tibble,看起来如下:

df <- tibble(return = c(NA,
                        0.120436251,
                        -0.019871515,
                        0.024876142,
                        -0.013786987,
                        -0.012571415),
             value = c(100,
                       NA,
                       NA,
                       NA,
                       NA,
                       NA))

我的目标是使用以下公式计算所有后续行(第一行除外)的值:(1+return)*lag(value)。预期输出应如下所示:

df_1 <- tibble(return = c(NA,
                        0.120436251,
                        -0.019871515,
                        0.024876142,
                        -0.013786987,
                        -0.012571415),
             value = c(100,
                       112.0436,
                       109.8171,
                       112.5490,
                       110.9973,
                       109.6019))

在base R中,i可以使用以下for循环:

df_1 = df

for (i in 2:nrow(df_1)){
  
  df_1$value[i] <- df_1$value[i-1]*(1+df_1$return[i])
}

在tidy中使用的函数可能是accumulate,然而,当使用下面的代码时,对于每一行我都收到一个列表:

df <- df %>% 
  mutate(Value = accumulate(value, ~if(is.na(.y)) .x*(1+df$return) else .y))

任何帮助都将不胜感激。

gcxthw6b

gcxthw6b1#

下面是一些方法。(通过将mutate替换为transform并使用基数R管道,可以很容易地将前两个转换为基数R。)

library(dplyr)
df %>% mutate(value = c(1, cumprod(1 + return[-1])) * value[1])

library(dplyr)
mult <- function(x, y) x * (1 + y)
df %>% mutate(value = Reduce(mult, init = value[1], return[-1], acc = TRUE))

library(dplyr)
library(purrr)
# mult defined above
df %>% mutate(value = accumulate(return[-1], mult, .init = value[1]))

相关问题