change a column from birth date to age in r

后端 未结 7 2063
灰色年华
灰色年华 2020-12-09 17:36

I am using data.table for the first time.

I have a column of about 400,000 ages in my table. I need to convert them from birth dates to ages.

What is the bes

7条回答
  •  遥遥无期
    2020-12-09 17:59

    Assume you have a data.table, you could do below:

    library(data.table)
    library(lubridate)
    # toy data
    X = data.table(birth=seq(from=as.Date("1970-01-01"), to=as.Date("1980-12-31"), by="year"))
    Sys.Date()
    

    Option 1 : use "as.period" from lubriate package

    X[, age := as.period(Sys.Date() - birth)][]
             birth                   age
     1: 1970-01-01  44y 0m 327d 0H 0M 0S
     2: 1971-01-01  43y 0m 327d 6H 0M 0S
     3: 1972-01-01 42y 0m 327d 12H 0M 0S
     4: 1973-01-01 41y 0m 326d 18H 0M 0S
     5: 1974-01-01  40y 0m 327d 0H 0M 0S
     6: 1975-01-01  39y 0m 327d 6H 0M 0S
     7: 1976-01-01 38y 0m 327d 12H 0M 0S
     8: 1977-01-01 37y 0m 326d 18H 0M 0S
     9: 1978-01-01  36y 0m 327d 0H 0M 0S
    10: 1979-01-01  35y 0m 327d 6H 0M 0S
    11: 1980-01-01 34y 0m 327d 12H 0M 0S
    

    Option 2 : if you do not like the format of Option 1, you could do below:

    yr = duration(num = 1, units = "years")
    X[, age := new_interval(birth, Sys.Date())/yr][]
    # you get
             birth      age
     1: 1970-01-01 44.92603
     2: 1971-01-01 43.92603
     3: 1972-01-01 42.92603
     4: 1973-01-01 41.92329
     5: 1974-01-01 40.92329
     6: 1975-01-01 39.92329
     7: 1976-01-01 38.92329
     8: 1977-01-01 37.92055
     9: 1978-01-01 36.92055
    10: 1979-01-01 35.92055
    11: 1980-01-01 34.92055
    

    Believe Option 2 should be the more desirable.

提交回复
热议问题