R:在纵向数据中插入丢失的日期,而不会丢失信息[重复]

问题描述 投票:-1回答:1

我在数据表中有一个纵向数据集,类似于下面的简化示例:

> head(data)
   Country     ID        Date         Value
1:   AT        AT6306    2012-11-01   16.2
2:   AT        AT6306    2012-11-02   12.2
3:   AT        AT6306    2012-11-03   11.3
4:   AT        AT6306    2012-11-04   14.2
5:   AT        AT6306    2012-11-05   17.3
6:   AT        AT6306    2012-11-06   12.5

> tail(data)
   Country     ID        Date         Value
1:   SE        SE0935    2014-06-25   16.2
2:   SE        SE0935    2014-06-26   12.2
3:   SE        SE0935    2014-06-27   11.3
4:   SE        SE0935    2014-06-28   14.2
5:   SE        SE0935    2014-06-29   17.3
6:   SE        SE0935    2014-06-30   12.5

ID是面板变量,它是唯一的,国家之间没有重叠。仅查看唯一值的日期范围为2012-10-232014-09-30。显然,每个DateID范围都不相同。此外,可能存在缺失值。为了使面板平衡,我想填补数据集的空白。

根据@akron的建议,调整答案here,然后执行以下操作:

data2 <- data[, CJ(ID=unique(ID), Date=unique(Date))]
setkey(data2, ID, Date)

data.new <- merge(data, data2, by=c("ID", "Date"), all.y = TRUE)
setkey(data.new, ID, Date)

使用选项all.y = TRUE,因此R为data中的每个缺失日期添加行。但是,如果IDDate中的行之前不存在,则现在所有字段均为空白。也就是说,我的数据看起来像这样

data

我确实希望> head(data.new) Country ID Date Value 1: NA AT6306 2012-10-23 NA 2: NA AT6306 2012-10-24 NA 3: NA AT6306 2012-10-25 NA 4: NA AT6306 2012-10-26 NA 5: NA AT6306 2012-10-27 NA 6: NA AT6306 2012-10-28 NA 为NA,因为它丢失了。但是,由于对于给定的ValueCountry不变,所以我希望填写该字段。

r date time-series data.table panel-data
1个回答
1
投票
ID

更新

您可以做的一个选择是

library(data.table)
DT <- data.table(dat)
setkey(DT, Date, Country, ID)
res <- DT[CJ(seq(min(Date), max(Date), by='1 day'), 
                        unique(Country), unique(ID))]

 head(res)
#    Country   ID       Date Value
#1:      AT  935 2012-11-01    NA
#2:      AT 6306 2012-11-01  16.2
#3:      SE  935 2012-11-01    NA
#4:      SE 6306 2012-11-01    NA
#5:      AT  935 2012-11-02    NA
#6:      AT 6306 2012-11-02  12.2

数据

DT <- data.table(dat)
DT[,CountryID:= paste(Country,ID)]
setkey(DT, Date, CountryID)
DT1 <- DT[CJ(unique(Date), unique(CountryID))][,
      c('Country', 'ID'):=  list(gsub("[ 0-9]", "", CountryID),
               gsub("[^ 0-9]", "", CountryID)),][,-5L]


head(DT1,3)
#     Country    ID       Date Value
#1:      AT  6306 2012-11-01  16.2
#2:      SE   935 2012-11-01    NA
#3:      AT  6306 2012-11-02  12.2

nrow(DT1)
#[1] 24
© www.soinside.com 2019 - 2024. All rights reserved.