代码之家  ›  专栏  ›  技术社区  ›  mmyoung77

当时间序列数据偏移且不完整时

r
  •  0
  • mmyoung77  · 技术社区  · 7 年前

    工作中的新客户有一个从3月开始到次年2月结束的会计日历:

    fiscalMonthLabels <- c("March", "April", "May", "June", 
      "July", "August", "September", "October", 
      "November", "December", "January", "February")
    

    但是,因为它们是新的,我们只有几个月的数据:

    library(lubridate)
    rawDate <- c("2018-09-01", "2018-10-01", "2018-11-01")
    actualMonth <- month(rawDate)
    newMonth <- rep(0, length(actualMonth))
    for (i in 1:length(actualMonth)) {
      if (actualMonth[i] == 1) {newMonth[i] <- 11} 
      else if (actualMonth[i] == 2) {newMonth[i] <- 12} 
      else {newMonth[i] <- actualMonth[i] - 2}
    }
    revenue <- c(123, 456, 789)
    
    df <- data.frame(rawDate, actualMonth, newMonth, revenue)
    df
         rawDate actualMonth newMonth revenue
    1 2018-09-01           9        7     123
    2 2018-10-01          10        8     456
    3 2018-11-01          11        9     789
    

    因此,当我尝试用会计月创建一个新因子时,我得到的错误是:

    fiscalMonth <- factor(newMonth, labels = fiscalMonthLabels)
    
    Error in factor(newMonth, labels = fiscalMonthLabels) : 
        invalid 'labels'; length 12 should be 1 or 3
    

    好像 factor 司令部正在寻找 actualMonth

    1 回复  |  直到 7 年前
        1
  •  1
  •   JasonAizkalns    7 年前

    你要分配 levels 也是:

    fiscalMonth <- factor(actualMonth, levels = 1:12, labels = fiscalMonthLabels)
    fiscalMonth
    [1] November December January 
    Levels: March April May June July August September October November December January February
    

    或者,既然你用的是 lubridate::month ,只需将label参数传递给month,month将返回一个有序因子:

    fiscalMonth <- month(actualMonth, label = TRUE)
    [1] Sep Oct Nov
    Levels: Jan < Feb < Mar < Apr < May < Jun < Jul < Aug < Sep < Oct < Nov < Dec