stack data frame by rows

spore234

I have a data set like this:

df <- data.frame(v1 = rnorm(12),
                 v2 = rnorm(12),
                 v3 = rnorm(12),
                 time = rep(1:3,4))

It looks like this:

> head(df)
          v1         v2         v3 time
1  0.1462583 -1.1536425  3.0319594    1
2  1.4017828 -1.2532555 -0.1707027    2
3  0.3767506  0.2462661 -1.1279605    3
4 -0.8060311 -0.1794444  0.1616582    1
5 -0.6395198  0.4637165 -0.9608578    2
6 -1.6584524 -0.5872627  0.5359896    3

I now want to stack row 1-3 in a new column, then rows 4-6, then 7-9 and so on.

This is may naive way to do it, but there must be fast way, that doesn't use that many helper variables and loops:

l <- list()
for(i in 1:length(df)) {
  l[[i]] <- stack(df[i:(i+2), -4])$values #time column is removed, was just for illustration
}
result <- do.call(cbind, l)

only base R should be used.

akrun

We can use split on the 'time' column

sapply(split(df[-4], cumsum(df$time == 1)), function(x) stack(x)$values)

Or instead of stack, unlist could be faster

sapply(split(df[-4], cumsum(df$time == 1)), unlist)

Based on the OP's code, it seems to be subsetting the rows based on the sequence of column

sapply(1:length(df), function(i) unlist(df[i:(i+2), -4]))

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related