用 NA 填充时间序列中缺失的月份 [英] filling missing month in time series with NA

查看:26
本文介绍了用 NA 填充时间序列中缺失的月份的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有数据集:年月数

2002-01    2.392909
2002-02    2.496800
2002-03    2.341897
2002-04    1.665625
2002-05    2.398261
2003-01    1.765912
2003-03    3.270870
2003-12    2.907812

我需要结束:

2002-01    2.392909
2002-02    2.496800
2002-03    2.341897
2002-04    1.665625
2002-05    2.398261
2002-06    NA
2002-07    NA
2002-08    NA
2002-09    NA
2002-10    NA
2002-11    NA
2002-12    NA
2003-01    1.765912
2003-02    NA
2003-03    3.270870
2002-04    NA
2003-05    NA
2003-06    NA
2003-07    NA
2003-08    NA
2003-09    NA
2003-10    NA
2003-11    NA
2003-12    2.907812

所有缺失的月份都会用 NA 填充,直到 12 月非常感谢任何想法!

all missing month will fill with NA, till Dec any ideas much appreciated!

推荐答案

这是一种方法.它设置了所有年月的列,然后将您的数据合并到其中,因此在您没有数据的地方留下空白.

Here is one way. It sets up a column of all the year-months and then merges your data into it, so blanks are left where you have no data.

merge(data.frame(V1=paste(rep(2002:2003,each=12), #the years
                          sprintf("%02d",1:12), #the months, padded with zeros
                          sep="-")),
      df, #your dataframe (assumes the first column is "V1")
      all.x=TRUE)

        V1       V2
1  2002-01 2.392909
2  2002-02 2.496800
3  2002-03 2.341897
4  2002-04 1.665625
5  2002-05 2.398261
6  2002-06       NA
7  2002-07       NA
8  2002-08       NA
9  2002-09       NA
10 2002-10       NA
11 2002-11       NA
12 2002-12       NA
13 2003-01 1.765912
14 2003-02       NA
15 2003-03 3.270870
16 2003-04       NA
17 2003-05       NA
18 2003-06       NA
19 2003-07       NA
20 2003-08       NA
21 2003-09       NA
22 2003-10       NA
23 2003-11       NA
24 2003-12 2.907812

这篇关于用 NA 填充时间序列中缺失的月份的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆