R: How to calculate the difference in years between a date and a year

爷,独闯天下 提交于 2019-12-11 05:54:42

问题


Is there a quick way to calculate the difference in years between a) a date (data$First.Trading.Day) eg. "2016-02-09" and b) a year (data$Founding.Year) e.g. "1999"

I already did the following, but do not get to a correct result:

data$Age <- difftime(data$First.Trading.Day, data$Founding.Year, "years")

then I made a new column with only the year of the First trading date and tried this:

data$First.Trading.Year <- format(as.Date(data$First.Trading.Day),"%Y")
data$Age <- (data$First.Trading.Year) - (data$Founding.Year)

this gives me an error message

I would really appreciate some help!


回答1:


A lubridate solution:

libray(lubridate)

date <- ymd("2016-02-09", "2012-05-19")
years_diff <- year(date) - 1999

# 17 13



回答2:


A=c('2017-01-01','2015-01-01')
B=c('2016-01-01','2014-01-01')
data=data.frame(A)
data$B=B
data$A <- format(as.Date(data$A),"%Y")
data$B <- format(as.Date(data$B),"%Y")
data$Age <- as.numeric(data$A) - as.numeric(data$B)
data
     A    B Age
1 2017 2016   1
2 2015 2014   1

The error from you code : Error in (data$A) - (data$B) : non-numeric argument to binary operator



来源:https://stackoverflow.com/questions/44783268/r-how-to-calculate-the-difference-in-years-between-a-date-and-a-year

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!