【问题标题】:How to loop the xirr function in r over multiple ID's如何在多个ID上循环r中的xirr函数
【发布时间】:2019-05-02 14:02:33
【问题描述】:

我想计算表中每个 ID 的 IRR(使用包 tvm 中的 xirr 函数),其中每个 ID 具有不同的行数。我相信我必须使用第一次出现到最后一次出现-1,但在那之后,我不知道该怎么做。有没有人有什么建议?

我在下面发布了一个示例数据框,为此我尝试使用 dplyr 中的 summarise 函数和函数 xirr 并编写一个 for 循环。没有成功。

exampledf<-data.frame(c(2, 2, 2, 3, 3, 3, 3, 3), c("2017-11-30", "2017-12-31", "2018-01-31", "2017-11-30", "2017-12-31", "2018-01-31", "2018-02-28", "2018-03-31"), c(-65000, 33000, 33000, -40000, 10250, 10250, 10000, 10500))
names(exampledf)<-c("ID","Date","CashFlow")


exampledf %>% group_by(ID) %>% summarise(
  IRR = xirr(cf = exampledf$CashFlow, d = exampledf$Date, tau = NULL, comp_freq = 12, interval = c(-1, 10)))

预期的结果应该是这样的:

     ID   IRR
1     2 0.127
2     3 0.125

目前,在运行汇总函数时,它会为两个 ID 返回相同的 IRR,但情况并非如此。我对 for 循环的尝试也没有成功,我们将不胜感激!

【问题讨论】:

    标签: r loops xirr


    【解决方案1】:

    我们需要删除summarise 中的example$,因为example$ 将选择整个列而不是每个“ID”中的“现金流”。此外,“日期”列类型应更改为Date

    library(dplyr)
    library(tvm)
    exampledf %>%
      mutate(Date = as.Date(Date)) %>%
      group_by(ID) %>% 
       summarise(
       IRR = xirr(cf =CashFlow, d = Date, 
          tau = NULL, comp_freq = 12, interval = c(-1, 10)))
    # A tibble: 2 x 2
    #     ID   IRR
    #  <dbl> <dbl>
    #1     2 0.121
    #2     3 0.119
    

    【讨论】:

      猜你喜欢
      • 2021-12-21
      • 2022-12-03
      • 2021-08-30
      • 2019-11-13
      • 1970-01-01
      • 2015-10-14
      • 1970-01-01
      • 2018-01-26
      • 2013-11-29
      相关资源
      最近更新 更多