How to Fix in R: Error in as.Date.numeric(x) : ‘origin’ must be supplied

One error you may encounter in R is:

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

This error usually occurs when you attempt to convert a number to a date in R, but fail to provide an origin date.

This tutorial shares exactly how to fix this error.

How to Reproduce the Error

Suppose we have the following data frame in R that shows the total sales made during various days by some company:

#create data frame
df <- data.frame(date=c(27, 140, 180, 200),
                 sales=c(12, 22, 30, 31))

#view data frame

  date sales
1   27    12
2  140    22
3  180    30
4  200    31

We can use the str() function to view the structure of the data frame:

#view structure of data frame

'data.frame':	4 obs. of  2 variables:
 $ date : num  27 140 180 200
 $ sales: num  12 22 30 31

We can see that the date and sales columns are both numeric.

Now suppose we attempt to convert the date column to a date format:

#attempt to convert date column to date format
df$date <- as.Date(df$date)

Error in as.Date.numeric(df$date) : 'origin' must be supplied

We receive an error because we we did not use the origin argument within the as.Date() function.

How to Fix the Error

The way to fix this error is to simply provide an origin date so that R knows how to convert the numbers to dates:

#convert date column to date format, using 2020-01-01 as origin date
df$date <- as.Date(df$date, origin="2020-01-01")

#view updated data frame

        date sales
1 2020-01-28    12
2 2020-05-20    22
3 2020-06-29    30
4 2020-07-19    31

By supplying an origin date, R converted the numbers to dates by adding the number of days to the origin supplied.

For example:

  • The first date value of 27 was converted to 2020-01-28 by adding 27 days to the origin date of 2020-01-01.
  • The second date value of 140 was converted to 2020-05-20 by adding 140 days to the origin date of 2020-01-01.

And so on.

We can also use the class() function to confirm that the new column is indeed a date:

#display class of date column

[1] "Date"

The new column is now a date instead of a number.

Additional Resources

The following tutorials explain how to troubleshoot other common errors in R:

How to Fix in R: names do not match previous names
How to Fix in R: longer object length is not a multiple of shorter object length
How to Fix in R: contrasts can be applied only to factors with 2 or more levels

Featured Posts

Leave a Reply

Your email address will not be published. Required fields are marked *