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

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

我正在尝试 运行 几个 ID 上的 xirr 函数,但我收到一条错误消息:

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

有什么方法可以删除没有符号更改的 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()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))

结果

    # 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