I have a data frame with the dates of births as one of the vectors. I am trying to find out the ages of all of these people, but running into issues.
The vector is set as:
dob
When I type:
age_calc(dob[1])
It will tell me the age of the first person in the data frame. However, I can't for the life of me figure out how to work it out for everyone in the data frame. I have tried
age_calc(dob)
Error in if (any(enddate < dob)) { :
missing value where TRUE/FALSE needed
I have tried
age_calc(dob[1:300])
Error in if (any(enddate < dob)) { :
missing value where TRUE/FALSE needed
I have also tried many other variations, but can't get it. Is anyone able to help me at all? It would be much appreciate
I can't make any promises since we don't have a sample of your data, but I would guess that you have some missing values in your dob object, which is causing the error. I'm put together the following example
library(eeptools)
#> Warning: package 'eeptools' was built under R version 4.0.5
#> Loading required package: ggplot2
dob <- rep(Sys.Date()-(365*10), 3)
age_calc(dob, units = "years")
#> [1] 9.991781 9.991781 9.991781
# Now let's force one of those to be NA
dob[2] <- NA
age_calc(dob, units = "years")
#> Error in if (any(enddate < dob)) {: missing value where TRUE/FALSE needed
# Created on 2021-08-26 by the reprex package (v2.0.1)
It seems that age_calc isn't well suited to handling missing values. I would probably approach this with the following function as a wrapper around age_calc to get the desired result:
age_calc_miss <- function(dob, enddate = Sys.Date(), units = "months", precise = TRUE){
retval <- rep(NA_real_, length(dob))
miss <- is.na(dob)
retval[!miss] <- eeptools::age_calc(dob = dob[!miss],
enddate = enddate,
units = units,
precise = precise)
retval
}
dob <- rep(Sys.Date()-(365*10), 3)
dob[2] <- NA
age_calc_miss(dob, units = "years")
#> [1] 9.991781 NA 9.991781
Created on 2021-08-26 by the reprex package (v2.0.1)
This above is an excellent solution. I provide an alternative using purrr that might only have convenience benefits (it doesn't need one to construct the wrappings function param list manually).
library(eeptools)
#> Warning: package 'eeptools' was built under R version 4.0.5
#> Loading required package: ggplot2
dob <- rep(Sys.Date()-(365*10), 3)
age_calc(dob, units = "years")
#> [1] 9.991781 9.991781 9.991781
# Now let's force one of those to be NA
dob[2] <- NA
library(purrr)
quiet_age_calc <- possibly(age_calc,otherwise = NA,quiet = TRUE)
map_dbl(dob,~quiet_age_calc(.x, units = "years"))