I am trying to create a variable "diff_in_days" that calculates the difference between 2 variables using the difftime function:
- ONSET_DATE and 2) DATE_OF_DEATH
This is the code I currently have:
humanyr2$diff_in_days<- difftime(humanyr2$DATE_OF_DEATH ,humanyr2$ONSET_DATE , units = c("days"))
When I run this, I get an error: "Error in as.POSIXlt.character(x, tz, ...) : character string is not in a standard unambiguous format"
My date variables are in the format: MM/DD/YYYY
Any help would be appreciated. Thank you!
CodePudding user response:
You could use lubridate
package with the ymd()
function:
To make calculations like subtraction with to dates you have to transform to Date class!
library(lubridate)
onset_date <- "01-02-2010"
date_of_death <- "23-09-2022"
diff <- dmy(date_of_death) - dmy(onset_date)
diff
Time difference of 4617 days