如何为面板数据集创建双向 table?

How to create a two way table for a panel data set?

我在R中设置了以下数据:

Country     Year       Population
   A        2000         1,000
   A        2001         1,100
   A        2002         1,200
   B        2000         1,150
   B        2001       
   B        2003         1,400
   C        2000       
   C        2001         1,000
   C        2003         1,100

其中空格表示缺失值。我正在尝试使用人口列可用数据的年份创建两种方式 table。像这样:

Country  2000  2001  2002
   A       1     1     1
   B       1     0     1
   C       0     1     1

您可以使用 dcast 将数据转换为宽格式。此外,您可以使用 dplyr 中的 spread

方法一:

library(data.table)
dcast(df[!is.na(df$Population),], formula = Country ~ Year, fun.aggregate = length)

print(df)
  Country 2000 2001 2002 2003
1       A    1    1    1    0
2       B    1    0    0    1
3       C    0    1    0    1

方法二:

df %>% 
    mutate(row_id = if_else(is.na(Population),0,1)) %>% 
    select(-Population) %>% 
    spread(Year, row_id,fill=0)

  Country 2000 2001 2002 2003
1       A    1    1    1    0
2       B    1    0    0    1
3       C    0    1    0    1