Almacomet
Almacomet

Reputation: 211

How to stack rows of data frame

I'm having trouble stacking rows in a data.frame into one row. My data looks something like this:

v1       v2      v3      index     
var1     ad      b1      1    
var2     sa      b2      2     
var3     4       b3      3     
var1     5       b4      1     
var2     6       b5      2    
var3     2       b6      3
.        .       .       . 
.        .       .       . 
.        .       .       . 

I'm trying to transpose the data so v1 becomes my colnames and they are also stacked. I'm familiar with the native transpose command t() and assigning the colnames as the first row. However, I'm not sure how to stack the rows. I did break up each group of rows (in three's) transposed and then binded them in a loop, but it's very slow, as my data set is 1gb.

var1   var2  var3
ad     sa     4
b1     b2     b3
5      6      2
b4     b5     b6
.      .      .
.      .      .
.      .      .

Thanks for any help!

Upvotes: 1

Views: 440

Answers (1)

h3rm4n
h3rm4n

Reputation: 4187

The recast function from reshape2 is well suited for this. But before you use that, you need to transform you index-column in a better grouping variable:

# transform 'index' into a grouping variable
dat$index <- cumsum(c(0, head(dat$index, -1) > tail(dat$index, -1)))

# reshape into the new format
library(reshape2)
recast(dat, variable + index ~ v1, id.var = c('v1','index'))[,3:5]

now your data looks like this:

  var1 var2 var3
1   ad   sa    4
2    5    6    2
3   b1   b2   b3
4   b4   b5   b6

Upvotes: 0

Related Questions