简体   繁体   English

如何在多个ID的r中循环xirr函数

[英]How to loop the xirr function in r over multiple ID's

I want to calculate the IRR (using the xirr function from package tvm) for each ID in a table where each ID has a different number of rows. 我想为表中的每个ID计算IRR(使用包tvm中的xirr函数),其中每个ID具有不同的行数。 I believe I have to use first occurrence to last occurrence-1, but after that, I am not sure what to do. 我相信我必须使用第一次出现到最后一次出现1,但是在那之后,我不确定该怎么做。 Does anyone have any suggestions? 有没有人有什么建议?

I have posted an example data frame below, for which I have tried using both the summarise function in dplyr with function xirr and to write a for loop. 我在下面发布了一个示例数据框,为此,我尝试在dplyr中将summary函数与xirr函数一起使用,并编写一个for循环。 No success. 没有成功

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)))

The expected results should be something like: 预期结果应类似于:

     ID   IRR
1     2 0.127
2     3 0.125

Currently when running the summarise function it returns the same IRR for both ID's which should not be the case. 当前,在运行summary函数时,它对两个ID返回相同的IRR,事实并非如此。 My attempt with the for loop was not successful either, any help here would be appreciated! 我对for循环的尝试也未成功,这里的任何帮助将不胜感激!

We need to remove the example$ in summarise as the example$ will select the entire column instead of the 'CashFlow' within each 'ID'. 我们需要从summarise删除example$ ,因为example$将选择整个列,而不是每个'ID'中的'CashFlow'。 In addition, the 'Date' column type should be changed to Date 此外,“日期”列类型应更改为“ 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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM