从r年龄确定出生日期

时间:2013-08-25 01:02:45

标签: r date-arithmetic

为模拟样本分配出生日期;以下作品,但忽略了闰年。

想知道是否有更精确(优雅)的方法?

# Simulate 10 persons with age evenly distributed 0 to 21
age <- runif(10, 0, 21)
# calc age in seconds
agesecs <- age*365*24*60*60
# subtract from right now to establish 'birthdate'
bday <- as.Date(Sys.time() - agesecs)
bday
[1] "2008-03-28" "1998-06-12" "2010-05-02" "2007-01-11" "2007-06-07"
[6] "1999-05-22" "2004-01-29" "2013-03-29" "1998-06-01" "2006-10-14"

1 个答案:

答案 0 :(得分:0)

difftime object在日期和时间算术方面表现出色。问题是它识别的单位不包括年份。所以,我用了几个星期来代替几年随机化,一个单位difftime接受。

    # Simulate 10 persons with age evenly distributed 0 to 21 (use weeks)
    agewks <- runif(10, 0, (21*52))
    # convert to difftime object
    agedt <- as.difftime(agewks, units="weeks")
    # above could be combined into single step
    # agewks <- as.difftime(runif(10, 0, (21*52)), units='weeks')
    # subtract from right now to establish a 'birthdate' for our simulated persons
    bday <- as.POSIXct(Sys.time() - agedt)
    bday
    [1] "1997-05-26 13:23:07 EDT" "2003-02-24 13:07:48 EST"
    [3] "2006-12-20 12:38:04 EST" "2002-01-02 15:17:14 EST"
    [5] "1993-10-07 15:49:19 EDT" "2001-05-04 04:05:29 EDT"
    [7] "2003-09-28 09:35:30 EDT" "1996-05-17 20:58:15 EDT"
    [9] "2008-08-09 14:17:24 EDT" "2011-05-09 23:26:04 EDT"
    # to create a date object use
    bday <- as.Date(Sys.time() - agedt)

感谢Carl和其他人对我的指导。欢迎采用替代和更好的方法。