【问题标题】:Computing Growth of a Variable in R计算 R 中变量的增长
【发布时间】:2017-11-17 10:42:24
【问题描述】:

我想用 R 计算数据框中的增长变量。

假设我有一个起始变量X=100 和一个向量Y,时间长度为 10,增长率为 f.e

Y<-c(0.04, 0.03, -0.02 ... 0.02)

是否有计算 X o.v.t. 增长率的解决方案,以便我得到一个初始值 X 的向量,例如: (100, 100*(1+0,04), (100*(1+0,04)*(1,03),...等)

我希望我能说清楚。

谢谢,

【问题讨论】:

  • 看看X*cumprod(1+Y)

标签: r rate


【解决方案1】:

@AEF 在上面的 cmets 中给出了很好且简单的答案。 只是使用purrr 包和函数accumulate 发布另一个解决方案。对于您的具体示例可能有点过多,但如果您想应用更复杂的函数/模式/方法,则很有用:

library(purrr)

# set of growth rates
gr_rates = c(0.04, 0.03, -0.02, 0.02)

# function to apply the general formula
f = function(x,r) {x*(1+r)}

# apply the function recursively and show intermediate results
# set the starting point as 100
accumulate(gr_rates, f, .init = 100)

# [1] 100.0000 104.0000 107.1200 104.9776 107.0772

【讨论】:

    【解决方案2】:

    我认为您正在寻找的是 cumprod 功能。这类似于计算金融中的财富指数。请尝试以下操作:

    library(tidyverse)
    df <- data.frame( changes = c(0.04, 0.03, -0.02, 0.02) ) %>% tbl_df()
    
    # Now calculate your growth rates, or wealth indexes, as follows:
    
    start_value <- 100
    
    df_growth_rate <- df %>% mutate( growth_rate = start_value * cumprod(1 + changes))
    

    【讨论】:

      【解决方案3】:

      我遇到了计算会计类输入值增长的问题。我写了以下函数。它将起始值作为输入 (x)、增长该值所需的周期数 (n) 以及增长率 (g)。您可以将该功能增长率明智地应用于您的价值x = 100

      growth_fct <- function(x, n, g){
      
        xrep <- rep(x, (n-1))
        for(i in seq_along(xrep)){
          xrep[i] <- xrep[i] * (1 + g)^i
        }
        x <- c(x, xrep)
        return(x)
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2017-11-27
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-10-16
        • 1970-01-01
        • 2018-01-14
        • 2022-06-22
        相关资源
        最近更新 更多