将数据框的列索引转换为Yearmon

时间:2020-03-11 21:25:28

标签: r date dplyr

我有以下数据框

{
  "name": "deployingdemo",
  "version": "1.0.0",
  "description": "",
  "main": "app.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
error-> "start": "node app.js",
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
    "ejs": "^6.11.3",
    "express": "^10.16.3"
  }
}

我想将列名称转换为格式为 yearmon 的日期序列,并以以下形状收集它们:

data_frame <- data.frame(sku = c("A","B","C"), forecast1 = c(1,2,3), forecast2 = c(4,5,6), forecast3 = c(7,8,9))

我尝试了以下操作:

colnames(data_frame)[2:4] <- c("2020_03","2020_04","2020_05")
gather(data_frame,"yearmon","forecast",2:4)

1 个答案:

答案 0 :(得分:1)

创建格式为yyyy-mm的列名称,执行gather并使用yearmon转换名为as.yearmon的列:

nc <- ncol(data_frame)
ym <- seq(as.yearmon("2020-03"), length = nc-1, by = 1/12)
names(data_frame)[-1] <- format(ym, "%Y-%m")

data_frame %>%
  gather("yearmon", "forecast", -1) %>%
  mutate(yearmon = as.yearmon(yearmon))

给予:

  sku  yearmon forecast
1   A Mar 2020        1
2   B Mar 2020        2
3   C Mar 2020        3
4   A Apr 2020        4
5   B Apr 2020        5
6   C Apr 2020        6
7   A May 2020        7
8   B May 2020        8
9   C May 2020        9