gpt4 book ai didi

r - 根据 r 中的年龄确定出生日期

转载 作者:行者123 更新时间:2023-12-02 04:59:10 24 4
gpt4 key购买 nike

为模拟样本指定出生日期;以下有效,但忽略了闰年。

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

# 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"

最佳答案

difftime 对象 在日期和时间运算方面做得很好。问题是它识别的单位不包括年份。因此,我没有按年进行随机化,而是使用周,一个 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 和其他人指导我完成上述工作。欢迎替代和更好的方法。

关于r - 根据 r 中的年龄确定出生日期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18424679/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com