簡體   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