用R中的循环或函数编写年月向量[关闭]

问题描述 投票:0回答:1

我想制作2018年至2020年之间的年月向量,而不要一一键入,例如2018-01、2018-02 ... 2020-01。

这是预期的结果

month_names <- c("2018-01", "2018-02", "2018-03", ..... "2020-01")

任何帮助将不胜感激。

r function sapply
1个回答
0
投票

您可以使用seq创建一个月度序列,然后使用format

month_names <- format(seq(as.Date("2018-04-01"), as.Date("2020-04-01"), 
                       by = 'month'), '%Y-%m')

 #[1] "2018-04" "2018-05" "2018-06" "2018-07" "2018-08" "2018-09" "2018-10"
 #[8] "2018-11" "2018-12" "2019-01" "2019-02" "2019-03" "2019-04" "2019-05"
#[15] "2019-06" "2019-07" "2019-08" "2019-09" "2019-10" "2019-11" "2019-12"
#[22] "2020-01" "2020-02" "2020-03" "2020-04"

[outer的另一种方式:

c(t(outer(2018:2020, sprintf("%02d", 1:12), paste, sep = "-")))
© www.soinside.com 2019 - 2024. All rights reserved.