I am new to R, but I've searched this topic a lot before posting here, because there are plenty of results in google and stackoverflow.
My dataframe has 3041 rows and several columns, DDN is Date of Birth in portuguese.
I've tried all these solutions from other topics, but none os these worked.
Age <- function(dob, age= today(), units = "years", floor = TRUE) {
calc.age = new_interval(DDN, idade) / duration(num = 1, units = units)
if (floor) return(as.integer(floor(calc.age)))
return(calc.age)}
Age <- as.Date (P4PA$DDN)
P4PA$Idade <- floor(age_calc(P4PA$DDN, units = "years"))
Age <- as.numeric(format(as.Date(Sys.time()),format="%Y"))-as.numeric(format(as.Date(DDN,format="%m/%d/%Y"),format="%Y"))
yourdata$age <- floor(age_calc(yourdata$birthdate, units = "years"))
age = function(from, to) {
from_lt = as.POSIXlt(from)
to_lt = as.POSIXlt(to)
age = to_lt$year - from_lt$year
ifelse(to_lt$mon < from_lt$mon |
(to_lt$mon == from_lt$mon & to_lt$mday < from_lt$mday),
age - 1, age)
}
And this: http://blog.jsonbecker.com/2013/06/calculating-age-in-r.html
head(P4PA) DDN 4/22/1956 12/26/1964 4/16/1963 1/28/1970 7/15/1972 1/18/1956
class(P4PA$DDN)
"factor"
I need to calculate age from this column with 3041 observations, but I cannot figure out how. I tried to change DDN class to numeric, but a message with Error appears. I really dont know what to do anymore. I thought it would be easy.
Thank you
First, copy and paste the function age_calc
from the blog post to which you linked into your R console (or RStudio console) and hit 'Enter' to store it.
The function takes 3 arguments: dob, enddate and units. The dob
argument needs to be of class Date
. Units can be days, months or years. Assuming that you want years, this should add a column age
to your data frame:
P4PA$age <- age_calc(as.Date(P4PA$DDN, "%m/%d/%Y"), units = "years")
P4PA
DDN age
1 4/22/1956 60
2 12/26/1964 52
3 4/16/1963 53
4 1/28/1970 47
5 7/15/1972 44
6 1/18/1956 61
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.