Negative age in R

Asked

Viewed 86 times

2

I have a database that I need to calculate the age of the limbs in it, below a sample taken with the dput.

base.teste <- c("04/03/73", "10/09/67", "21/12/74", "17/04/76", "25/03/66", 
"11/03/73", "06/08/79")

I need to calculate the age of all members at the end of November, 30/11/2017. Transofmrei the data on dates, pelo lubridate and executed the following code:

library(lubridate)
idade <- floor(as.numeric(difftime(data.fim.mes, base.teste, units = "days"))/365.25)

But in the result I end up getting negative ages:

44 -50  42  41 -49  44  38

Does anyone know why or have a better way of calculating?

  • 3

    If you notice, after the transformation of base.teste in Date (I used the formula as.Date), the years 66 and 67 are converted to 2066 and 2067 respectively.

  • I’m using the dmy(base.teste) and the result is :1973-03-04 2067-09-10 1974-12-21 1976-04-17 2066-03-25 1973-03-11 1979-08-06

  • 1

    Similarly, the year 67 is being converted to 2067, hence the negative ages. I added an answer using the package chron that worked the way expected for your test bench.

1 answer

4


A solution using the package chron

library(chron)
base.teste <- c("04/03/73", "10/09/67", "21/12/74", "17/04/76", "25/03/66", "11/03/73", "06/08/79")
base.teste <- chron(base.teste, format = c(dates = "d/m/y")) 
data.fim.mes <- "30/11/17"
data.fim.mes <- chron(data.fim.mes, format = c(dates = "d/m/y"))

idade <- floor(as.numeric(difftime(data.fim.mes, base.teste, units = "days"))/365.25)

results in:

idade
[1] 44 50 42 41 51 44 38
  • It worked here!. I hadn’t even noticed the dates of 2067

Browser other questions tagged

You are not signed in. Login or sign up in order to post.