Convert days to years using R lubridate

Asked

Viewed 49 times

0

Assuming the following dataframe:

library(dplyr)
library(lubridate)
df<-data.frame(inicio= ymd(19800101), fim=ymd(20200101)) %>% 
  mutate(dif=fim-inicio)

     inicio        fim        dif
1 1980-01-01 2020-01-01 14610 days

How do I convert those 14610 days into years (or months, or weeks)?

SEQUENCE

df %>% 
  mutate(em.anos= time_length(dif, unit = "year"))

  inicio        fim          dif  em.anos
1 1980-01-01 2020-01-01 40.0274 days 0.109589

2 answers

3


  • I tried, but still could not: I did the sequence in the original post

  • Use interval(inicio, fim) instead of subtraction, and then you use the time_length

2

With difftime:

library(dplyr)
library(lubridate)

In weeks weeks:

data.frame(inicio= ymd(19800101), fim=ymd(20200101)) %>% 
  mutate(dif = difftime(fim, inicio, units = "weeks"))

In years (division of weeks obtained by the number of weeks present in a year ~ 52.25):

data.frame(inicio= ymd(19800101), fim=ymd(20200101)) %>% 
  mutate(dif = difftime(fim, inicio, units = "weeks") / 52.25)

You could also get seconds, minutes, hours and days by entering the parameters below in the argument units:

“secs”, “mins”, “hours”, “days”
  • 1

    It’s not easier em.anos = difftime(fim, inicio)/365.25?

Browser other questions tagged

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