繁体   English   中英

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

[英]“Origin” must be supplied issue with the function in r: possibly environment/namespace issue

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

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

什么可能导致这个?

谢谢!

请注意,如果您已经学会了如何阅读该部分,那么?as.Date的Usage部分就有线索:

## 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", ...)

as.Date.numeric的'origin'参数没有默认值,而class character的方法在“dots”之前没有'origin'参数。 您应该发现查看函数本身将提供类似的确认。

我自己也遇到了这个问题。 如果要转换的字段是数字,则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)
}

希望这可以帮助!

暂无
暂无

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

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