Ashling Mc Phillips
Ashling Mc Phillips

Reputation: 13

Add months and days to year

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

Answers (1)

zx8754
zx8754

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

Related Questions