重新排列 R 中的数据框以进行面板分析

Rearranging data frame in R for panel analysis

我在重新排列我的数据框以使其适合面板分析时遇到问题。 原始数据是这样的(有所有国家和50年,那只是头):

head(suicide_data_panel)

country     variable  1970  1971 
Afghanistan suicide   NA    NA          
Afghanistan unempl    NA    NA          
Afghanistan hci       NA    NA      
Afghanistan gini      NA    NA          
Afghanistan inflation NA    NA          
Afghanistan cpi       NA    NA          

我希望它是:

country     year    suicide  unempl 
Afghanistan 1970      NA    NA          
Afghanistan 1971      NA    NA          
Afghanistan 1972      NA    NA      
Afghanistan 1973      NA    NA          
Afghanistan 1974      NA    NA          
Afghanistan 1975      NA    NA

这样我就可以 运行 面板回归。我试过使用 dcast,但我不知道如何计算不同的年份:

suicide <- dcast(suicide_data_panel, country~variable, sum)

此命令将导致仅考虑最后一年:

head(suicide)

    country         account    alcohol     
1   Afghanistan     -18.874843  NA  
2   Albania         -6.689212   NA  
3   Algeria         NA          NA  
4   American Samoa  NA          NA      
5   Andorra         NA          NA      
6   Angola          7.000035    NA

它按字母顺序对变量进行排序。请帮忙。

您可以尝试使用 tidyverse 包:

library(tidyverse)

suicide_data_panel %>%
  gather(year, dummy, -country, -variable) %>%
  spread(variable, dummy)

遵循 reshape 方法。

tm <- by(dat, dat$variable, reshape, varying=3:4, idvar="country", 
         direction="long", sep="", timevar="year", drop=2)
res <- cbind(el(tm)[1:2], data.frame(mapply(`[[`, tm, 3)))
res
#         country year         hci    suicide     unempl
# DE.1970      DE 1970  1.51152200  1.3709584  0.6328626
# AT.1970      AT 1970 -0.09465904 -0.5646982  0.4042683
# CH.1970      CH 1970  2.01842371  0.3631284 -0.1061245
# DE.1971      DE 1971  0.63595040 -0.0627141 -1.3888607
# AT.1971      AT 1971 -0.28425292  1.3048697 -0.2787888
# CH.1971      CH 1971 -2.65645542  2.2866454 -0.1333213

数据

set.seed(42)
dat <- cbind(expand.grid(country=c("DE", "AT", "CH"),
                         variable=c("suicide", "unempl", "hci"),
             stringsAsFactors=F), x1970=rnorm(9), x1971=rnorm(9))

您可以首先执行此操作:使用带有 ID 变量 "country" 和 "variable" 的 MELT 函数;第二:使用 dcast 函数将 "variable" 转换为单独的列。