计算从日期开始的年数

时间:2016-09-11 09:38:14

标签: r

我已经从Facebook以06/23/1993的格式检索了我的生日,我希望将这个生日变成我的年龄。

这是我到目前为止的代码:

install.packages("eeptools")
library(eeptools)

as.POSIXct(facebook$birthday, tz = "", format = "%m/%d/%Y", origin="1970-01-01")
as.Date(facebook$birthday, format = "%m/%d/%Y")

facebook$age <- floor(age_calc(facebook$birthday, units = "years"))

在前2行后,它返回:

as.POSIXct(facebook$birthday, tz = "", format = "%m/%d/%Y", origin="1970-01-01")
#[1] "1993-06-23 CEST"
as.Date(facebook$birthday, format = "%m/%d/%Y")
#[1] "1993-06-23"

在最后一行之后我收到此错误:

  

age_calc错误(facebook $ birthday,units =&#34; years&#34;):     dob和enddate都必须是Date类对象

如果有人能帮助我,我将不胜感激:)

解决! 编辑:我忘了在最后一行插入as.Date:

facebook$age <- floor(age_calc(as.Date(facebook$birthday, units = "years"))

1 个答案:

答案 0 :(得分:1)

我不确定是什么失败了。这就是我的工作,它对我有用:

install.packages("eeptools")
library(eeptools)

date = "06/23/1993"
date = as.POSIXct(date, tz = "", format = "%m/%d/%Y", origin="1970-01-01")

floor(age_calc(as.Date(date), units = "years"))
#[1] 23

或者没有POSIXct转换(根据G. Grothendieck的评论):

floor(age_calc(as.Date(date, format = "%m/%d/%Y"), units = "years"))