"Origin" must be supplied issue with the function in r: possibly environment/namespace issue

StackOverflow https://stackoverflow.com/questions/22599701

  •  19-06-2023
  •  | 
  •  

Pergunta

I have a function that produces the first date of each month:

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

where fDNM is

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)
}

everything works well when I apply this function to an index. However, when I include this function to a custom package I get

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

What could cause this?

Thanks!

Foi útil?

Solução

Notice that the Usage section of ?as.Date has clues if you have learned how to read that section.:

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

The 'origin' parameter for as.Date.numeric does not have a default value, whereas the method for class character does not have an 'origin' parameter prior to the "dots". You should find that looking at the functions themselves will provide similar confirmation.

Outras dicas

I just ran into this problem myself. as.Date needs an origin if the field to be converted is numeric.

if you chage you code as below it should work.

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)
}

Hope this helps!

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top