r - 子集具有完整时间维度的面板数据

标签 r data.table panel

我有一个面板数据,你可能会注意到有些人在某些时候缺少观察。例如,“C”是 2001 年的缺失数据点,“D”是 2002 和 2003 年的缺失数据点。

> mydata
    id year sales profit
 1:  A 2000  2000    200
 2:  A 2001  2050    245
 3:  A 2002  2100    290
 4:  A 2003  2150    335
 5:  B 2000  2200    380
 6:  B 2001  2250    425
 7:  B 2002  2300    470
 8:  B 2003  2350    515
 9:  C 2000  2400    560
10:  C 2002  2500    650
11:  C 2003  2550    695
12:  D 2000  2600    740
13:  D 2001  2650    785

我试过类似下面的东西
subset(mydata, year==c(2000:2003)

结果如下所示。
   id year sales profit
1:  A 2000  2000    200
2:  A 2001  2050    245
3:  A 2002  2100    290
4:  A 2003  2150    335
5:  B 2000  2200    380
6:  B 2001  2250    425
7:  B 2002  2300    470
8:  B 2003  2350    515
9:  C 2000  2400    560
Warning message:
In year == c(2000:2003) :
  longer object length is not a multiple of shorter object length

我需要的是包含完整时期的数据,从 2000 年开始到 2003 年结束。在这种情况下,它会是这样的。
   id year sales profit
1:  A 2000  2000    200
2:  A 2001  2050    245
3:  A 2002  2100    290
4:  A 2003  2150    335
5:  B 2000  2200    380
6:  B 2001  2250    425
7:  B 2002  2300    470
8:  B 2003  2350    515

感谢您抽出宝贵时间并提前回答,但如果答案更简单一些,我将不胜感激,因为我非常缺乏经验并且刚刚开始学习 R。

最佳答案

您可以尝试以下操作:

library(data.table)
mydata[, ind := all(2000:2003 %in% year), id][(ind)]
#    id year sales profit  ind
# 1:  A 2000  2000    200 TRUE
# 2:  A 2001  2050    245 TRUE
# 3:  A 2002  2100    290 TRUE
# 4:  A 2003  2150    335 TRUE
# 5:  B 2000  2200    380 TRUE
# 6:  B 2001  2250    425 TRUE
# 7:  B 2002  2300    470 TRUE
# 8:  B 2003  2350    515 TRUE

使用“tidyverse”:
library(tidyverse)
mydata %>% 
  group_by(id) %>% 
  filter(all(2000:2003 %in% year))

示例数据(这是您将来应该共享的方式):
mydata <- structure(list(id = c("A", "A", "A", "A", "B", "B", "B", "B", 
    "C", "C", "C", "D", "D"), year = c(2000L, 2001L, 2002L, 2003L, 
    2000L, 2001L, 2002L, 2003L, 2000L, 2002L, 2003L, 2000L, 2001L
    ), sales = c(2000L, 2050L, 2100L, 2150L, 2200L, 2250L, 2300L, 
    2350L, 2400L, 2500L, 2550L, 2600L, 2650L), profit = c(200L, 245L, 
    290L, 335L, 380L, 425L, 470L, 515L, 560L, 650L, 695L, 740L, 785L
    )), .Names = c("id", "year", "sales", "profit"), row.names = c(NA, 
    13L), class = c("data.table", "data.frame"))

关于r - 子集具有完整时间维度的面板数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47930570/

相关文章:

c++ - fread/fwrite 引入垃圾值

R数据.表: evaluating address of an object in parent frame

javascript - ExtJS 列布局,移动可调整大小的面板而不重叠

r - 如何在R中保存数据框

r - 如何自动对齐不同ggplots的轴限制

r - 更新 R 中的 csv header ,无需重写整个文件

delphi - 当控件之间有间距时使用 AlignWithMargins 是一个好的选择吗?

javascript - 空 bootstrap 列上的 Jquery 可排序问题

r - 如果 value 中的 a 值等于 R 中的上一行,则删除整行

java - 关于将 R 集成到 Web 应用程序中