简体   繁体   English

删除特定变量中没有符号更改的键的所有行

[英]Remove all rows for a key with no sign change in a specific variable

I am trying to run an xirr function on several ID's but I get an error message saying: 我试图在几个ID上运行xirr函数,但我收到一条错误消息:

        Error in uniroot(xnpv, interval = interval, cf = cf, d = d, tau = tau, :
no sign change found in 1000 iterations

Is there any way to remove all rows for the ID's that do not have a sign change (as ID 2 in the example below)? 有没有办法删除没有符号更改的ID的所有行(如下例中的ID 2)?

library(tvm)
library(dplyr)

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$Date <- as.Date(exampledf$Date)

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

Any help with this would be appreciated! 任何帮助都将不胜感激!

Combining the any() and sign() functions in the following way will test whether any of the values in column CashFlow are positive ( any(sign(CashFlow) == 1 ) and negative ( any(sign(CashFlow) == -1) ) 以下列方式组合any()sign()函数将测试CashFlow列中的任何值是否为正( any(sign(CashFlow) == 1否定( any(sign(CashFlow) == -1)

library(dplyr)

exampledf %>% 
    group_by(ID) %>% 
    filter(any(sign(CashFlow) == 1) && any(sign(CashFlow) == -1))

Result 结果

    # A tibble: 5 x 3
    # Groups:   ID [1]
         ID Date       CashFlow
      <dbl> <fct>         <dbl>
    1     3 2017-11-30   -40000
    2     3 2017-12-31    10250
    3     3 2018-01-31    10250
    4     3 2018-02-28    10000
    5     3 2018-03-31    10500

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

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