1

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!

Carina
  • 11
  • 1
  • 3

2 Answers2

4

A lubridate solution:

libray(lubridate)

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

# 17 13
J_F
  • 9,956
  • 2
  • 31
  • 55
0
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

BENY
  • 317,841
  • 20
  • 164
  • 234