我有一个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))
任何帮助都将不胜感激。
1条答案
按热度按时间gcxthw6b1#
下面是一些方法。(通过将
mutate
替换为transform
并使用基数R管道,可以很容易地将前两个转换为基数R。)