最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

r - Finding a date from an original date by subtracting the number of weeks between both dates - Stack Overflow

programmeradmin4浏览0评论

New to R, and am trying to find the date of conception from date of mother's delivery, i.e. taking weeks away from a date to find the origin date

For example:

I have the delivery dates of the women, and their gestation age in weeks, but need to estimate the date of conception.

Example data:

id date_delivery gest_age_weeks
1 01-01-2010 40
2 31-12-2012 38

New to R, and am trying to find the date of conception from date of mother's delivery, i.e. taking weeks away from a date to find the origin date

For example:

I have the delivery dates of the women, and their gestation age in weeks, but need to estimate the date of conception.

Example data:

id date_delivery gest_age_weeks
1 01-01-2010 40
2 31-12-2012 38

etc

Expected output would be:

id date_conception
1 27-03-2009
2 09-04-2012

I did consider converting my date of delivery variable into weeks and working back from that but not sure how to convert back into a date

Share Improve this question edited Jan 20 at 15:21 Andre Wildberg 19.1k4 gold badges18 silver badges36 bronze badges asked Jan 20 at 14:53 KerrieKerrie 193 bronze badges 3
  • 1 The package lubridate (included in the tidyverse meta-package) has nice functions to handle dates. Ex. dmy("01-01-2010") - weeks(40) . Take a look to this chapter/whole book: r4ds.hadley.nz/datetimes – VinceGreg Commented Jan 20 at 15:23
  • Friendly warning: never ever EVER write your own date-handling code. It will always fail somewhere you didn't think of. – Carl Witthoft Commented Jan 20 at 16:52
  • This question can't be answered until we know what the actual contents of those cells are. Strings? Posix? magic? – Carl Witthoft Commented Jan 20 at 16:54
Add a comment  | 

1 Answer 1

Reset to default 2

In R, you can treat dates like numbers - i.e. "some_date - 5" would be five days before "some_date". So perhaps the simplest option would be to subtract weeks * 7:

df$date_conception <- df$date_delivery - (df$gest_age_weeks * 7)

#   id date_delivery gest_age_weeks date_conception
# 1  1    2010-01-01             40      2009-03-27
# 2  2    2012-12-31             38      2012-04-09

Data

df <- read.table(text = "id   date_delivery    gest_age_weeks    
1      01-01-2010          40
2      31-12-2012          38", h = TRUE)
df$date_delivery <- as.Date(df$date_delivery, format = "%d-%m-%Y")
发布评论

评论列表(0)

  1. 暂无评论