0
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?

1 Answer 1

1

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)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.