Adrian
Adrian

Reputation: 9793

R: How to store date in a data.frame and prevent R from converting it to numbers?

mydat <- data.frame(id = c(1, 1, 2), date_of_entry = c(NA, NA, NA))
mydate <- structure(17189, class = "Date")
> mydate
[1] "2017-01-23"

mydate is a date, and I want to populate the date_of_entry column with that mydate for id == 1. If I tried:

mydat$date_of_entry[mydat$id == 1] <- mydate
> mydat
  id date_of_entry
1  1         17189
2  1         17189
3  2            NA

However, I want the date_of_entry column to contain the actual date, not a numerical representation of the date in R. How can I go about this?

Upvotes: 0

Views: 768

Answers (1)

Ronak Shah
Ronak Shah

Reputation: 388982

Make date_of_entry column of Date class before assigning the value (currently it is of class "logical").

mydat$date_of_entry <- as.Date(mydat$date_of_entry)
mydat$date_of_entry[mydat$id == 1] <- mydate
mydat

#  id date_of_entry
#1  1    2017-01-23
#2  1    2017-01-23
#3  2          <NA>

Also, those numbers are numeric representation of dates so you can also convert them to dates from numbers.

#dataframe
mydat <- data.frame(id = c(1, 1, 2), date_of_entry = c(NA, NA, NA))
#date converted to number
mydat$date_of_entry[mydat$id == 1] <- mydate
#convert it back to date
mydat$date_of_entry <- as.Date(mydat$date_of_entry)

Upvotes: 1

Related Questions