年龄和年龄范围的计算从出生日期开始



我有一个数据帧(称为基线(,其中有一列出生日期(DOB(,格式为mm/dd/yyyy。我想根据出生日期计算截至"今天"的年龄,并将这些年龄放入一个名为"年龄"的新列中。我还想计算年龄范围(18-35,36-44(,并将其放入另一个名为年龄范围的专栏中。(18-35岁甚至可能是0,36-44岁可能是1(。

这就是我计算年龄的方法:

baseline$Age <- age_calc(as.Date(baseline$DOB, "%m/%d/%Y"), enddate=Sys.Date(), 
units="years", precise=TRUE)

但我得到了这个错误:

Error in mapply(seq, as.POSIXct(start), as.POSIXct(end), by = "years",  : 
zero-length inputs cannot be mixed with those of non-zero length

我没有试图计算年龄范围——我真的不知道从哪里开始。

看起来像是一个包问题,但您不需要任何问题。

你似乎有这样的数据:

head(dat, 3)
#          DOB something
# 1 02/21/1993 0.6756073
# 2 03/01/1924 0.9828172
# 3 10/31/1945 0.7595443

首先,定义"today"

today <- as.Date('2022-01-01')  ## hardcoded
# today <- Sys.Date()  ## alternatively dynamic

然后,使用within,依次定义这样的变量。

dat <- within(dat, {
DOB <- as.Date(DOB, "%m/%d/%Y")  ## coerce to `"Date"` class
age <- as.numeric(today - DOB)/365.25  ## calculate years
age_cat <- cut(age, c(0, 17, 35, 44, Inf),  ## cut in categories
c('<18', '18-35', '36-44', '>44'))
age2 <- round(age)  ## maybe
})
dat
#           DOB something age2 age_cat        age
# 1  1993-02-21 0.6756073   29   18-35  28.859685
# 2  1924-03-01 0.9828172   98     >44  97.837098
# 3  1945-10-31 0.7595443   76     >44  76.169747
# 4  1921-01-30 0.5664884  101     >44 100.919918
# 5  2000-07-16 0.8496897   21   18-35  21.462012
# 6  1924-11-21 0.1894739   97     >44  97.111567
# 7  1992-04-07 0.2712866   30   18-35  29.735797
# 8  1937-04-06 0.8281585   85     >44  84.739220
# 9  2009-10-09 0.6932048   12     <18  12.229979
# 10 1978-03-11 0.2405447   44   36-44  43.811088
# 11 2014-10-31 0.0429888    7     <18   7.170431
# 12 2011-01-15 0.1404791   11     <18  10.962355
# 13 1962-03-21 0.2163854   60     >44  59.783710
# 14 1930-09-24 0.4793986   91     >44  91.271732
# 15 1992-04-20 0.1974103   30   18-35  29.700205

以下是cut()的详细功能:

setNames(cut(16:46, c(0, 17, 35, 44, Inf), c('<18', '18-35', '36-44', '>44')), 16:46)
#    16    17    18    19    20    21    22    23    24    25    26 
#   <18   <18 18-35 18-35 18-35 18-35 18-35 18-35 18-35 18-35 18-35 
#    27    28    29    30    31    32    33    34    35    36    37 
# 18-35 18-35 18-35 18-35 18-35 18-35 18-35 18-35 18-35 36-44 36-44 
#    38    39    40    41    42    43    44    45    46 
# 36-44 36-44 36-44 36-44 36-44 36-44 36-44   >44   >44 

数据:

set.seed(42)
dat <- data.frame(DOB=strftime(sample(seq.Date(as.Date('1900-01-01'), 
as.Date('2022-01-01'), 'day'), 15),
"%m/%d/%Y"),
something=runif(15))

最新更新