首页 > 解决方案 > 将数据框作为参数传递时,用户定义的函数返回错误值

问题描述

我有一个函数来进行如下插值:

interpola <- function(DF, vlBase, interpolY = TRUE) {
  DataFrameInterpol <- data.frame(DF)
  FunctionVlBase <- as.numeric(vlBase)
  InterpolaVar <- interpolY

  if (InterpolaVar) n <- 1 else n <- 2

  df1 <- filter(data.frame(DataFrameInterpol),
                data.frame(DataFrameInterpol[, n]) <= FunctionVlBase) %>% top_n(1)
  x1 <- df1[, 1]
  y1 <- df1[, 2]

  df2 <- filter(data.frame(DataFrameInterpol),
                data.frame(DataFrameInterpol[, n]) >= FunctionVlBase) %>% top_n(-1)
  x2 <- df2[, 1]
  y2 <- df2[, 2]

  # Se interpolY == TRUE
  # Retorna Y
  if (InterpolaVar) {
    # Checa se vlBase está na DF
    if (x1 == x2) {
      return(y1)
    }
    else {
      tmp <- (FunctionVlBase - x1) * (y2 - y1) / (x2 - x1) + y1
      return(tmp)
    }
  }

  # Se interpolY <> TRUE
  # Retorna X
  else if (!InterpolaVar) {
    # Checa se vlBase está na DF
    if (y1 == y2) {
      return(x1)
    }
    else {
      tmp <- (FunctionVlBase - y1) * (x2 - x1) / (y2 - y1) + x1
      return(tmp)
    }
  }
} 

该函数接收一个带有 2 列 (x,y) 的 DataFrame,它们是插值的基值,一个用作我想要插值的点的值和一个布尔参数来定义我是否应该在 x 下进行插值或 y 访问。

当 vlBase 是数字参数时,该函数工作正常,但是当我尝试传递 DataFrame 列(例如mutate(BaseDate, interpola(InterpolaDF, BaseData$Values)))时,它给了我错误的结果。

我有以下数据框:InterpolaDF

BusinessDaysToMat RateAcum
0 1.000246
6 1.001476
29 1.007173
48 1.011959
70 1.017700
90 1.023123

日期向量:

Date    Refdate BusinessDaysToMat
2018-07-24 2018-07-24                 0
2018-07-25 2018-07-24                 1
2018-07-26 2018-07-24                 2
2018-07-27 2018-07-24                 3
2018-07-28 2018-07-24                 3
2018-07-29 2018-07-24                 3
2018-07-30 2018-07-24                 4
2018-07-31 2018-07-24                 5
2018-08-01 2018-07-24                 6
2018-08-02 2018-07-24                 7
2018-08-03 2018-07-24                 8
2018-08-04 2018-07-24                 8
2018-08-05 2018-07-24                 8
2018-08-06 2018-07-24                 9
2018-08-07 2018-07-24                10

如果我执行类似interpola(InterpolaDF, 22)我得到 1.002467(这是预期回报)的事情,但如果interpola(InterpolaDF, dateVector$BusinessDaysToMat)在 BusinessDaysToMat = 10 的行上执行,我得到 1.000246 的回报

标签: ruser-defined-functionsdplyr

解决方案


推荐阅读