简体   繁体   English

一年中增加几个月和几天

[英]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. 我想在只有可用年份的所有日期上添加“ 01-01”,以便每个日期都具有相同的格式。

Any suggestion is welcome. 任何建议都欢迎。

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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM