【问题标题】:calculation of age based on any preveous time根据以前的任何时间计算年龄
【发布时间】:2018-12-06 15:50:19
【问题描述】:

有没有办法找到这样的问题的解决方案;

如果我在 2010 年 1 月 10 日的年龄是 2 岁,那么 2012 年 4 月 10 日的年龄是多少。

亲切的问候

【问题讨论】:

  • 这很简单,但确切的解决方案取决于您的数据结构。您有可以使用 dput 共享的示例吗?

标签: r date datetime date-formatting date-conversion


【解决方案1】:

只需使用difftime() 计算差异,然后添加年龄。像这样的:

earlier_age <- 2
diff <- as.numeric(difftime(latest_date, earlier_date), units="years") 
#make sure that dates are actually date objects (using as.Date())
new_age <- diff + earlier_age


#So for your example:
latest_date <- as.Date("10/April/2012", format = "%d/%B/%Y")
earlier_date <- as.Date("10/jan/2010", format = "%d/%b/%Y")
earlier_age <- 2

diff <- as.numeric(difftime(latest_date, earlier_date), units="days")/365.25
new_age <- diff + earlier_age

您可以根据需要将单位更改为周、小时等

【讨论】:

  • 我得到units="years"的“指定的无效单位”。我错过了什么?
  • 使用其他单位,如周或天,然后进行转换。
【解决方案2】:

您可以设置日期,例如:

x <- as.Date("2010-01-10")
y <- as.Date("2012-04-10")

>y-x
Time difference of 821 days

从这里开始,只需将其添加到 2 年。让我知道这是否有帮助!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-05-26
    • 1970-01-01
    • 2016-07-20
    • 1970-01-01
    • 1970-01-01
    • 2013-10-31
    • 1970-01-01
    相关资源
    最近更新 更多