0

My data has a variable for baseline age, and a follow up variable with number of months since baseline observation. Both are numeric vectors with whole numbers only. I want to calculate age at follow up. When I parse these variables to period objects using lubridate and add them together I get results like 5 years 14 months. Ideally - I'd like this to be 6 years 2 months.

Example

library(dplyr)
library(lubridate)
library(magrittr)

set.seed(080617)
df <- 
  tibble(year = sample(20),
     month = sample(20))

df %<>% 
  mutate(year = years(year)) %>% 
  mutate(month = months(month)) %>%
  mutate(age = (year + month))
df

I have tried using df$age <- as.period(df$age, units = "years") to no avail.

Any suggestions?

davidhen
  • 579
  • 6
  • 10
  • I'd suggest using the `%/%` and `%%` operators on your month variable and use 12 as the base. For example `13 %/% 12` equals 1 and `13 %% 12` also equals 1, which would imply it's 1 year and 1 month. You should be able to use these in your calculations of `year` and `month`. – tblznbits Jun 08 '17 at 18:01

1 Answers1

1

This should get you the result you're looking for. I changed the column names to year.col and month.col, to make it easier to follow the logic

library(dplyr)
library(lubridate)
library(magrittr)

set.seed(080617)
df <- 
  tibble(year.col = sample(20),
         month.col = sample(20))

df %<>% 
  mutate(year.col = years(year.col)) %>% 
  mutate(month.col = months(month.col)) %>%
  mutate(age = year.col + years(month(month.col) %/% 12) + months(month(month.col) %% 12))
Matt Jewett
  • 3,249
  • 1
  • 14
  • 21
  • Hadn't seen/used integer division or modulo before - very handy! This works great for the minimal example. Unfortunately when I apply to my *actual* data I get the error `Error in as.POSIXlt.numeric(x) : 'origin' must be supplied`. The code is the same as above with only the relevant column names changed. Any ideas? – davidhen Jun 11 '17 at 11:17
  • Actually figured it out myself. I also had `mice` and `VIM` packages loaded. Remove those and it works fine. Not sure of the actual clash but hey - it works! – davidhen Jun 11 '17 at 18:01