必须在r:可能的环境/命名空间问题中为函数提供“Origin”问题

时间:2014-03-24 01:41:33

标签: r xts

我有一个产生每月第一个日期的函数:

firstDayNextMonth <- function(x)
#
# Wrapper for the function above - applies the firstDayNextMonth to the vector
#
{
  return(as.Date(sapply(x, fDNM)))
}

其中fDNM是

fDNM <- function(x)
#
# Computes the date of the first day of the next month
#
{ 
  if (as.numeric(format(x,format="%m"))==12)
  {
    nextMonth = 1
    Yr = as.numeric(format(x,format="%Y"))+1
  }else{
    nextMonth = as.numeric(format(x,format="%m"))+1
    Yr = as.numeric(format(x,format="%Y"))
  }
  y = as.Date(paste(Yr, nextMonth, '01', sep='-'), format = "%Y-%m-%d")
  return(y)
}

将此函数应用于索引时,一切正常。但是,当我将此功能包含在自定义包中时,我得到了

Error in as.Date.numeric(sapply(x, fDNM)) : 'origin' must be supplied

是什么导致这个?

谢谢!

2 个答案:

答案 0 :(得分:2)

请注意,?as.Date的“使用”部分有线索,如果您已学会如何阅读该部分。:

## S3 method for class 'character'
as.Date(x, format = "", ...)
## S3 method for class 'numeric'
as.Date(x, origin, ...)
## S3 method for class 'POSIXct'
as.Date(x, tz = "UTC", ...)

&#39;起源&#39; as.Date.numeric的参数没有默认值,而类字符的方法没有&#39;来源&#39; &#34;点&#34;之前的参数。您应该发现查看函数本身将提供类似的确认。

答案 1 :(得分:1)

我自己也遇到了这个问题。如果要转换的字段是数字,则as.Date需要原点。

如果你让代码变成如下,它应该有用。

fDNM <- function(x)
#
# Computes the date of the first day of the next month
#
{ 
  if (as.numeric(format(x,format="%m"))==12)
  {
    nextMonth = 1
    Yr = as.numeric(format(x,format="%Y"))+1
  }else{
    nextMonth = as.numeric(format(x,format="%m"))+1
    Yr = as.numeric(format(x,format="%Y"))
  }
  y = as.Date(as.character(paste(Yr, nextMonth, '01', sep='-')), format = "%Y-%m-%d")
  return(y)
}

希望这有帮助!

相关问题