【问题标题】:How can I add months to a date in a for loop and append the result to a list or dataframe?如何在 for 循环中将月份添加到日期并将结果附加到列表或数据框中?
【发布时间】:2021-10-18 18:27:59
【问题描述】:

目标是获得一个包含两列的数据框:第一列是月份,第二列是年份。我希望 for 循环能从现在开始两年。考虑到我还没有找到解决方案,所以我将 for 循环留空。

D <- data.frame(month(Sys.Date()), year(Sys.Date()))
D <- rename(D, Month = month.Sys.Date..., Year = year.Sys.Date...)

for (x in 1:24) {
     D1 <- return() 
}

【问题讨论】:

    标签: r loops date


    【解决方案1】:

    我们不需要循环。一个选项是将paste 'Year'、'Month' 一起转换为yearmon 类(来自zoo)并添加一系列月份

    library(zoo)
     as.yearmon(paste0(D$Year, "-", D$Month)) + 0:24/12
    

    【讨论】:

    • 我收到此错误:D$Year 中的错误:'closure' 类型的对象不是子集我在 Azure ML 中使用它,所以我不知道它是否有什么需要使用他们的 R 版本
    • @EAG 必须和你的Ddata.frame 相关。在示例中,我看到两列“年”和“月”
    猜你喜欢
    • 2016-07-24
    • 2021-07-29
    • 2011-10-02
    • 1970-01-01
    • 2020-07-26
    • 2019-09-21
    • 2015-04-27
    • 2020-04-25
    • 1970-01-01
    相关资源
    最近更新 更多