繁体   English   中英

如何重塑这个复杂的数据框?

[英]How to reshape this complicated data frame?

这是我数据的前4行;

  X...Country.Name Country.Code                               Indicator.Name
1           Turkey          TUR           Inflation, GDP deflator (annual %)
2           Turkey          TUR Unemployment, total (% of total labor force)
3      Afghanistan          AFG           Inflation, GDP deflator (annual %)
4      Afghanistan          AFG Unemployment, total (% of total labor force)
     Indicator.Code     X2010
1 NY.GDP.DEFL.KD.ZG  5.675740
2    SL.UEM.TOTL.ZS 11.900000
3 NY.GDP.DEFL.KD.ZG  9.437322
4    SL.UEM.TOTL.ZS        NA

我希望将数据重塑为两个列,每个指标代码之一,并且我希望每一行都对应一个国家,如下所示;

Country Name NY.GDP.DEFL.KD.ZG SL.UEM.TOTL.ZS
Turkey       5.6         11.9
Afghanistan  9.43        NA

我想我可以使用Excel做到这一点,但是我想学习R方式,这样我每次遇到问题时都不必依靠excel。 如果需要的话, 这里是数据处理。

编辑:我实际上想要3个列,每个指标一个,国家名称一个。

紧贴底座R,使用reshape 我自由地清理了列名。 在这里,我仅向您显示输出的几行。 卸下head即可看到完整的输出。 假设您的data.frame名为“ mydata”。

names(mydata) <- c("CountryName", "CountryCode", 
                   "IndicatorName", "IndicatorCode", "X2010")
head(reshape(mydata[-c(2:3)], 
             direction = "wide", 
             idvar = "CountryName", 
             timevar = "IndicatorCode"))
#       CountryName X2010.NY.GDP.DEFL.KD.ZG X2010.SL.UEM.TOTL.ZS
# 1          Turkey                5.675740                 11.9
# 3     Afghanistan                9.437322                   NA
# 5         Albania                3.459343                   NA
# 7         Algeria               16.245617                 11.4
# 9  American Samoa                      NA                   NA
# 11        Andorra                      NA                   NA

基本R中的另一个选项是xtabs ,但是NA被替换为0

head(xtabs(X2010 ~ CountryName + IndicatorCode, mydata))
#                 IndicatorCode
# CountryName      NY.GDP.DEFL.KD.ZG SL.UEM.TOTL.ZS
#   Afghanistan             9.437322            0.0
#   Albania                 3.459343            0.0
#   Algeria                16.245617           11.4
#   American Samoa          0.000000            0.0
#   Andorra                 0.000000            0.0
#   Angola                 22.393924            0.0

xtabs的结果是一个matrix ,因此,如果需要data.frame ,请使用as.data.frame.matrix包装输出。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM