计算R中的年龄 [英] Calculate ages in R

查看:373
本文介绍了计算R中的年龄的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在R中有两个数据框。一个框有一个人的出生年份:

I have two data frames in R. One frame has a persons year of birth:

YEAR
/1931
/1924

,然后另一列显示了最近的时间。

and then another column shows a more recent time.

RECENT
09/08/2005
11/08/2005

我想做的是减去年数,以便可以按年数计算他们的年龄,但是我不确定该如何处理。请问有帮助吗?

What I want to do is subtract the years so that I can calculate their age in number of years, however I am not sure how to approach this. Any help please?

推荐答案

以下函数采用Date对象的向量并计算年龄,正确地计算了leap年。似乎是比任何其他答案都更简单的解决方案。

The following function takes a vectors of Date objects and calculates the ages, correctly accounting for leap years. Seems to be a simpler solution than any of the other answers.

age = function(from, to) {
  from_lt = as.POSIXlt(from)
  to_lt = as.POSIXlt(to)

  age = to_lt$year - from_lt$year

  ifelse(to_lt$mon < from_lt$mon |
         (to_lt$mon == from_lt$mon & to_lt$mday < from_lt$mday),
         age - 1, age)
}

这篇关于计算R中的年龄的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆