1

I have two columns in a data frame, and I'd like to interweave them to be a single column. For example, suppose:

col1 <- c(1,2,3,4)
col2 <- c(5,6,7,8)
df <- cbind(col1, col2)

I'd like the result to look something like:

> df$col

1
5
2
6
3
7
4
8

Any help would be greatly appreciated! Thanks.

pdw5
  • 33
  • 6

1 Answers1

4

If you wrap the c function around a matrix object (which is what df is above), it will "unwrap them in column-dominant manner (except it needs to be created with rbind so that the interleaving will occur):

c(rbind(col1,col2))
[1] 1 5 2 6 3 7 4 8

If you want it to print at the console as though it were a "column vector" in matrix parlance you could `cbind that result to get a one column matrix object:

cbind( c(rbind(col1,col2)) )
     [,1]
[1,]    1
[2,]    5
[3,]    2
[4,]    6
[5,]    3
[6,]    7
[7,]    4
[8,]    8
IRTFM
  • 258,963
  • 21
  • 364
  • 487