[R] More elegant way of stacking the data

David Winsemius dwinsemius at comcast.net
Tue Nov 25 00:28:46 CET 2014


On Nov 24, 2014, at 3:12 PM, Dimitri Liakhovitski wrote:

> I have the data frame 'df' and my desired solution 'out'.
> I am sure there is a more elegant R-way to do it - without a loop.
> 
> df = data.frame(a=1:5,b=letters[1:5],c1=1:5,c2=2:6,c3=3:7,c4=4:8)
> mylist=NULL
> for(i in 1:4){
>  myname<-paste("c",i,sep="")
>  mylist[[i]]<-df[c("a","b",myname)]
>  names(mylist[[i]])<-c("a","b","c")
> }
> out<-do.call(rbind,mylist)
> out
> 

Observe the wonders of recycling in dataframes. If you wanted to drop the last column from this it would be the same modulo changing one column nmae.

 cbind( df[1:2], stack(df[-c(1:2)] )  )
#
   a b values ind
1  1 a      1  c1
2  2 b      2  c1
3  3 c      3  c1
4  4 d      4  c1
5  5 e      5  c1
6  1 a      2  c2
7  2 b      3  c2
8  3 c      4  c2
9  4 d      5  c2
10 5 e      6  c2
11 1 a      3  c3
12 2 b      4  c3
13 3 c      5  c3
14 4 d      6  c3
15 5 e      7  c3
16 1 a      4  c4
17 2 b      5  c4
18 3 c      6  c4
19 4 d      7  c4
20 5 e      8  c4

-- 

David Winsemius
Alameda, CA, USA



More information about the R-help mailing list