如何重塑以下表格?

时间:2015-04-21 10:01:08

标签: r

这里有几个类似的问题,但我没有将它们应用到我的案例中。我有很多像这样的表:

GDP

time   |    AT    |    BE   |     BG    |     CF    | : United kingdom
2014Q4 |   4564   |  4646   |    6541   |     122   | :
2014Q3 |   1234   |  5789   |    3545   |     3546  | :
2014Q2 |   1456   |   354   |    3541   |     3543  | :
:      |    :     |    :    |     :     |      :    | :
1990Q1 |   1234   |  3546   |    6546   |     5466  |

REER: 类似的表等。

如何将它们重塑为以下样式:

       Country | time   |    GDP |  REER  |   :..
            AT | 1990Q1 |   4564 |  4646  |   6541  |    122  | :
            AT | 1990Q2 |   1234 |  5789  |   3545  |   3546  | :
            AT | 1990Q3 |   1456 |   354  |   3541  |   3543  | 
             : |  :     |   :    |   :    |     :   |      :  | :
United Kingdom | 2014Q4 |   1234 |  3546  |   6546  |   5466  |

代码

setwd ("D:/Documents/R/eurostatData")

library (SmarterPoland)
library(reshape)
library (xlsx)
# Write to xls file --------------------------------------------------------
save.xlsx <- function (file, ...)
{
  require(xlsx, quietly = TRUE)
  objects <- list(...)
  fargs <- as.list(match.call(expand.dots = TRUE))
  objnames <- as.character(fargs)[-c(1, 2)]
  nobjects <- length(objects)
  for (i in 1:nobjects) {
    if (i == 1)
      write.xlsx(objects[[i]], file, sheetName = objnames[i])
    else write.xlsx(objects[[i]], file, sheetName = objnames[i],
                append = TRUE)
  }
  print(paste("Workbook", file, "has", nobjects, "worksheets."))
}

# load TOC
TOC <- grepEurostatTOC("Production") # get everything about Production
TOC2 <- getEurostatTOC()
View(TOC)
# END TOC

dat_raw <- getEurostatRCV("sts_inpr_q") # quaterly

# how many unique values are?
unique(dat_raw$indic_bt)
unique(dat_raw$nace_r2) # initialy I need C - manufacturing
unique(dat_raw$time) # 1980-20104

production <- cast(dat_raw,  time ~ geo, subset= nace_r2=="C" & s_adj=="GROSS" )


# RESHAPING
# !!!!nothing to write, since the steps I did were not successful.!!!!


save.xlsx("data.xlsx", production, turnover_dom, turnover_ndom, import_price,  producer_prices, labour, GCF, gdp, inflation)

1 个答案:

答案 0 :(得分:0)

您可以使用tidyr包中的聚集。

    GDP <- gather(GDP_table, Country, GDP, -time)
    REER <- gather(REER_table, Country, REER, -time)

然后使用合并功能将它们组合在一起。

    data <- merge(GDP, REER)

我希望这会有所帮助。