将r中的出生日期更改为年龄 [英] change a column from birth date to age in r
本文介绍了将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?
推荐答案
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
[1] 46.73333 224.83118
[1] 46.73333 224.83118
age_calc(x[1],x[2], units = "years") # but you can set it to years
[1] 3.893151 18.731507
[1] 3.893151 18.731507
floor(age_calc(x[1],x[2], units = "years"))
[1] 3 18
[1] 3 18
为您的数据
yourdata$age <- floor(age_calc(yourdata$birthdate, units = "years"))
假设您要使用整数年作为年龄.
assuming you want age in integer years.
这篇关于将r中的出生日期更改为年龄的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文