本文介绍了将r中的出生日期更改为年龄的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是第一次使用data.table.

I am using data.table for the first time.

我的桌子上有大约40万个年龄的列.我需要将其从出生日期转换为年龄.

I have a column of about 400,000 ages in my table. I need to convert them from birth dates to ages.

做到这一点的最佳方法是什么?

What is the best way to do this?

推荐答案

摘录自此博客条目,我在eeptools程序包中找到了age_calc函数.它可以处理极端情况(cases年等),检查输入并看起来很健壮.

From the comments of this blog entry, I found the age_calc function in the eeptools package. It takes care of edge cases (leap years, etc.), checks inputs and looks quite robust.

library(eeptools)
x <- as.Date(c("2011-01-01", "1996-02-29"))
age_calc(x[1],x[2]) # default is age in months
age_calc(x[1],x[2], units = "years") # but you can set it to years
floor(age_calc(x[1],x[2], units = "years"))

为您的数据

yourdata$age <- floor(age_calc(yourdata$birthdate, units = "years"))

假设您要使用整数年作为年龄.

assuming you want age in integer years.

这篇关于将r中的出生日期更改为年龄的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

11-02 18:58