Reputation:
How do I initialize an empty data frame with a Date column in R?
I've tried a number of things, but they all generate an error message when I try to append a row with a date in the correct column. For example:
> test <- data.frame(date=as.Date(character()), var1 = as.numeric(), var2 = as.numeric())
> str(test)
'data.frame': 0 obs. of 3 variables:
$ date: 'Date' num(0)
$ var1: num
$ var2: num
> test <- rbind(test, c(as.Date("2020-01-01"), 123, 456))
Error in as.Date.numeric(e) : 'origin' must be supplied
Initializing the first column as an integer and then adding the "Date" class to it generates the same error:
> test <- data.frame(date=integer(0), var1=as.numeric(), var2=as.numeric())
> str(test)
'data.frame': 0 obs. of 3 variables:
$ date: int
$ var1: num
$ var2: num
> class(test$date) <- "Date"
> str(test)
'data.frame': 0 obs. of 3 variables:
$ date: 'Date' int(0)
$ var1: num
$ var2: num
> test <- rbind(test, c(as.Date("2020-01-01"), 123, 456))
Error in as.Date.numeric(e) : 'origin' must be supplied
I've also searched for this error message, but the examples I have found all deal with converting a number into a date. I haven't been able to find any examples in my context.
What's the correct way to initialize the date column so that I can add formatted dates to it as above?
Thanks!
Upvotes: 5
Views: 3451
Reputation: 4949
library(tidyverse)
df = tibble(
date = as.Date(x = integer(0), origin = "2000-01-01")
)
Upvotes: 4
Reputation: 887531
The issue is more likely due to concatenation as vector
cannot have multiple class
. We can pass a data.frame
rbind(test, setNames(data.frame(as.Date("2020-01-01"), 123, 456),
names(test)))
-output
date var1 var2
1 2020-01-01 123 456
Upvotes: 3