几个月到整数R

Ser*_*lla 8 r date

这是我正在处理的数据帧的一部分.第一列代表年份,第二列代表月份,第三列代表当年该月份的观察数量.

2005 07    2
2005 10    4
2005 12    2
2006 01    4
2006 02    1
2006 07    2
2006 08    1
2006 10    3
Run Code Online (Sandbox Code Playgroud)

我有2000年到2018年的观察.我想对这些数据运行内核回归,所以我需要从日期类向量创建一个连续整数.例如,2000年1月将是​​1,2001年1月将是​​13,2002年1月将是​​25,依此类推.有了它,我将能够运行内核.后来,我需要翻译它(1将是2000年1月,2将是2000年2月,依此类推)来绘制我的模型.

lmo*_*lmo 6

只需使用一点代数:

df$cont <- (df$year - 2000L) * 12L + df$month
Run Code Online (Sandbox Code Playgroud)

您可以使用模数和整数除法向后.

df$year <- df$cont %/% 12 + 2000L
df$month <- df$cont %% 12 # 12 is set at 0, so fix that with next line.
df$month[df$month == 0L] <- 12L
Run Code Online (Sandbox Code Playgroud)

这里%%是模数运算符,%/%是整数除法运算符.有关?"%%"这些算法和其他算术运算符的解释,请参阅.


phi*_*ver 5

你能做的就是以下几点.首先创建一个日期data.frame,expand.grid所以我们有2000年1月到2018年的所有年份和月份.接下来按正确的顺序排列并最后添加一个订单列,以便2000 01从1开始,2018 12是228.如果将其与原始表合并,则会得到以下结果.然后,您可以删除不需要的列.并且因为您有一个日期表,您可以根据订单列返回年份和月份列.

dates <- expand.grid(year = seq(2000, 2018), month = seq(1, 12))
dates <- dates[order(dates$year, dates$month), ]
dates$order <- seq_along(dates$year)


merge(df, dates, by.x = c("year", "month"), by.y = c("year", "month"))

  year month obs order
1 2005    10   4    70
2 2005    12   2    72
3 2005     7   2    67
4 2006     1   4    73
5 2006    10   3    82
6 2006     2   1    74
7 2006     7   2    79
8 2006     8   1    80
Run Code Online (Sandbox Code Playgroud)

数据:

df <- structure(list(year = c(2005L, 2005L, 2005L, 2006L, 2006L, 2006L, 2006L, 2006L), 
                     month = c(7L, 10L, 12L, 1L, 2L, 7L, 8L, 10L), 
                     obs = c(2L, 4L, 2L, 4L, 1L, 2L, 1L, 3L)), 
                class = "data.frame", 
                row.names = c(NA, -8L))
Run Code Online (Sandbox Code Playgroud)