Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
576 views
in Technique[技术] by (71.8m points)

r - Recognition and conversion of birth dates into ages

When I read an excel file in R, a column of birth dates has some of its values converted to 5-digit integers (e.g. line 3). I guess they represent the number of days?

Here I would like to convert both the dates and the integers in the column 'DOB' into years (i.e. ages). I am using the age_calc function from eeptools package. Therefore I would like some help in converting all the values in the column into proper dates, so that I can use the age_calc function without returning errors. Thanks in advance.

df1[1:5,1:5]:

  first_name last_name gender past_3_years_bike_related_purchases DOB       
  <chr>      <chr>     <chr>  <chr>                               <chr>     
1 Chickie    Brister   Male   86                                  1957-07-12
2 Morly      Genery    Male   69                                  1970-03-22
3 Ardelis    Forrester Female 10                                  27269     
4 Lucine     Stutt     Female 64                                  1979-01-28
5 Melinda    Hadlee    Female 34                                  1965-09-21

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can handle those dates separately.

#Index which have all numbers in it. 
inds <- grepl('^\d+$', df1$DOB)
#Create an empty column
df1$dob <- as.Date(NA)
#Change normal dates to date
df1$dob[!inds] <- as.Date(df1$DOB[!inds])
#Change excel date to dates.
df1$dob[inds] <- as.Date(as.numeric(df1$DOB[inds]), origin = "1899-12-30")
df1

#  first_name last_name gender        DOB        dob
#1    Chickie   Brister   Male 1957-07-12 1957-07-12
#2      Morly    Genery   Male 1970-03-22 1970-03-22
#3    Ardelis Forrester Female      27269 1974-08-28
#4     Lucine     Stutt Female 1979-01-28 1979-01-28
#5    Melinda    Hadlee Female 1965-09-21 1965-09-21

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...