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

R 如何为面板数据集创建双向表?,r,panel,R,Panel,我在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

我在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
其中,空格表示缺少的值。我正在尝试创建一个双向表,其中包含人口列的可用数据年数。大概是这样的:

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

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

方法1:

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
方法2:

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

谢谢,这正是我需要的。