问题描述
我想用lubridate
来计算给出他们的出生日期和今天的日期的年龄.现在我有这个:
I would like to use lubridate
to calculate age in years given their date of birth and today's date. Right now I have this:
library(lubridate)
today<-mdy(08312015)
dob<-mdy(09071982)
today-dob
这给了我他们几天的年龄.
which gives me their age in days.
推荐答案
这是我要采用的lubridate
方法:
interval(dob, today) / years(1)
得出32
年的答案.
请注意,该函数将抱怨它无法表达该年剩余时间.这是因为年份不是固定的概念,即leap年为366,非-年为365.您可以获得有关周数和天数的更详细的答案:
Note that the function will complain that it cannot express the remainder of the fraction of the year. This is because year is not a fixed concept, i.e. 366 in leap years and 365 in non-leap years. You can get an answer with more detail in regard to the number of weeks and days:
interval_period = interval(dob, today)
full_year = interval_period %/% years(1)
remaining_weeks = interval_period %% years(1) %/% weeks(1)
remaining_days = interval_period %% years(1) %% weeks(1) %/% days(1)
sprintf('Your age is %d years, %d weeks and %d days', full_year, remaining_weeks, remaining_days)
# [1] "Your age is 32 years, 51 weeks and 1 days"
请注意,我使用%/%
进行除法,并使用%%
作为模数,以减去整年/周后的剩余周数/天.
Note that I use %/%
for division and %%
as modulo to get the remaining weeks/days after subtracting the full years/weeks.
这篇关于时效性与时效性的时差?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!