Replacing part of date in R column

295 Views Asked by At

There are examples of replacing values in a single vector of a data frame in R with some other value. e.g. Replace a value in a data frame based on a conditional (`if`) statement in R & Replace numbers in data frame column in R?

I have slight variation of the problem, a data frame (athletes) with some errors in year of DOB, and I want to go through this and replace all instances where the year is 00yy-mm-dd with 19yy-mm-dd

I tried athletes$DOB[athletes$DOB == 00] to initially subset the values but that didn't work

              Name                    Country Height Weight Sex        DOB Gold Silver Bronze
1         Lamusi A People's Republic of China    170     60   M 0089-06-02    0      0      0
2       A G Kruger   United States of America    193    125   M 1979-02-18    0      0      0
3   Jamale Aarrass                     France    187     76   M 1981-11-15    0      0      0
4 Abdelhak Aatakni                    Morocco     NA     NA   M 0088-02-09    0      0      0
5  Maria Abakumova         Russian Federation    178     85   F 1986-01-15    0      0      0
6        Luc Abalo                     France    182     80   M 0084-09-06    0      0      0
1

There are 1 best solutions below

2
On BEST ANSWER

Try sub

athletes$DOB <- as.Date(sub('^0{2}', '19', athletes$DOB))
athletes$DOB
#[1] "1989-06-02" "1979-02-18" "1981-11-15" "1988-02-09" "1986-01-15"
#[6] "1984-09-06"