将数据展平在一个框架中

时间:2015-02-25 16:22:03

标签: r

如何以长格式压缩已存在于数据框中的数据? (我不确定我是否正确定义了我的问题,但下面的例子应该是清楚的。)

初始数据框:

   Region       District                    Data
1  Arusha Arusha (Rural)          Area ('000'ha)
2                         Production ('000'tons)
3                                Yield (tons/ha)
4         Arusha (Urban)          Area ('000'ha)
5                         Production ('000'tons)
6                                Yield (tons/ha)
7                 Karatu          Area ('000'ha)
8                         Production ('000'tons)
9                                Yield (tons/ha)

所需数据框

   Region       District                    Data
1  Arusha Arusha (Rural)          Area ('000'ha)
2  Arusha Arusha (Rural)  Production ('000'tons)
3  Arusha Arusha (Rural)         Yield (tons/ha)
4  Arusha Arusha (Urban)          Area ('000'ha)
5  Arusha Arusha (Urban)  Production ('000'tons)
6  Arusha Arusha (Urban)         Yield (tons/ha)
7  Arusha         Karatu          Area ('000'ha)
8  Arusha         Karatu  Production ('000'tons)
9  Arusha         Karatu         Yield (tons/ha)

暂定

production<-structure(list(Region = c("Arusha", "", "", "", "", "", "", "", 
                            ""), District = structure(c("Arusha (Rural)", "", "", "Arusha (Urban)", 
                                                        "", "", "Karatu", "", ""), .Dim = c(9L, 1L), .Dimnames = list(
                                                          NULL, "District")), Data = c(" Area ('000'ha)", " Production ('000'tons)", 
                                                                                       " Yield (tons/ha)", " Area ('000'ha)", " Production ('000'tons)", 
                                                                                       " Yield (tons/ha)", " Area ('000'ha)", " Production ('000'tons)", 
                                                                                       " Yield (tons/ha)")), .Names = c("Region", "District", "Data"
                                                                                       ), row.names = c(NA, 9L), class = "data.frame") 
apply(production[2], 1,function(x){if(x=="") x=x[-1]})

0 个答案:

没有答案