[R] transposing a data frame from horizontal to vertical (stacking)

Dimitri Liakhovitski dimitri.liakhovitski at gmail.com
Tue Jun 29 21:38:41 CEST 2010


Thank you very much for a reference to "reshape".
I found that melt(MyData) - and then resorting - gives me exactly what I want!
Dimitri


On Tue, Jun 29, 2010 at 1:46 PM, Henrique Dallazuanna <wwwhsd at gmail.com> wrote:
> Try this:
>
> reshape(MyData, direction = 'long', varying = list(c('jan', 'feb')), idvar =
> 2:3)
>
> On Tue, Jun 29, 2010 at 2:22 PM, Dimitri Liakhovitski
> <dimitri.liakhovitski at gmail.com> wrote:
>>
>> Hello, everyone!
>> I have a very simple task - I have a data frame (see MyData below) and
>> I need to stack the data (see result below).
>> I wrote the syntax below - it's very basic and it does what I need.
>> But I am sure what I am trying to do is a very typical task and there
>> must be a much shorter/more elegant way of doing it.
>> Any advice?
>>
>> Thank you very much!
>>
>>
>>
>> MyData<-data.frame(names=c("John","Mary","Paul","Debby"),jan=c(10,15,20,25),feb=c(1,2,3,4))
>> (MyData)
>> months<-names(MyData)[-1]
>> people<-as.character(MyData[[1]])
>>
>> ### Creating a temp matrix with people as columns and months as rows:
>> transposed<-apply(MyData[-1],1,t)
>>
>> ### Putting vertical data (months as rows) - for each person - into a
>> list:
>> list.of.stacked<-list()
>> for(i in 1:ncol(transposed)){
>>
>>  list.of.stacked[[i]]<-as.data.frame(matrix(ncol=3,nrow=length(months)))
>>        names(list.of.stacked[[i]])<-c("month","values","person")
>>        list.of.stacked[[i]][["month"]]<-months
>>        list.of.stacked[[i]][["values"]]<-transposed[1:nrow(transposed),i]
>>        list.of.stacked[[i]][["person"]]<-people[i]
>> }
>> (list.of.stacked)
>>
>> ### Creating a data frame from the list:
>> result<-do.call(rbind,list.of.stacked)
>> (result)
>>
>>
>> --
>> Dimitri Liakhovitski
>> Ninah Consulting
>> www.ninah.com
>>
>> ______________________________________________
>> R-help at r-project.org mailing list
>> https://stat.ethz.ch/mailman/listinfo/r-help
>> PLEASE do read the posting guide
>> http://www.R-project.org/posting-guide.html
>> and provide commented, minimal, self-contained, reproducible code.
>
>
>
> --
> Henrique Dallazuanna
> Curitiba-Paraná-Brasil
> 25° 25' 40" S 49° 16' 22" O
>



-- 
Dimitri Liakhovitski
Ninah Consulting
www.ninah.com



More information about the R-help mailing list