Reputation: 13
I have a data frame in which a variable contains dates with different formats:
1970-01-09
1974
1970
1987-05-28
1970-06-01
1980
I would like to add "01-01" to all the dates where I only have the year available in order to have the same format for every date.
Any suggestion is welcome.
Upvotes: 0
Views: 71
Reputation: 56149
Using anytime package:
library(anytime)
x <- c("1970-01-09","1974","1970","1987-05-28","1970-06-01","1980")
anydate(x)
# [1] "1970-01-09" "1974-01-01" "1970-01-01" "1987-05-28" "1970-06-01" "1980-01-01"
Or use paste:
ifelse(nchar(x) == 4, paste(x, "01-01", sep = "-"), x)
Upvotes: 3