gregmacfarlane
gregmacfarlane

Reputation: 2283

"Merge" table row-by-row in R

I have two (or more) tables of equal dimensions in R.

table1 <- as.table(matrix("TOP", nrow=4, ncol=2 )) 
table2 <- as.table(matrix("BOTTOM", nrow=4, ncol=2 )) 
> table1
  A   B  
A TOP TOP
B TOP TOP
C TOP TOP
D TOP TOP
> table2
  A      B     
A BOTTOM BOTTOM
B BOTTOM BOTTOM
C BOTTOM BOTTOM
D BOTTOM BOTTOM

I want to bind them together row-by-row. By contrast, rbind gives me

> rbind(table1,table2)
  A        B       
A "TOP"    "TOP"   
B "TOP"    "TOP"   
C "TOP"    "TOP"   
D "TOP"    "TOP"   
A "BOTTOM" "BOTTOM"
B "BOTTOM" "BOTTOM"
C "BOTTOM" "BOTTOM"
D "BOTTOM" "BOTTOM"

when what I want is

 > something(table1,table2, byrow=TRUE)
   A        B       
  A "TOP"    "TOP"   
  A "BOTTOM" "BOTTOM"  
  B "TOP"    "TOP"   
  B "BOTTOM" "BOTTOM"
  C .....

Upvotes: 0

Views: 2037

Answers (3)

texb
texb

Reputation: 547

Another attempt at handcrafting:

stopifnot(nrow(table1)==nrow(table2))
interleaved <- rep(seq(nrow(table1)),each=2)+c(0,nrow(table1))
rbind(table1,table2)[interleaved,]

Upvotes: 0

Ricardo Saporta
Ricardo Saporta

Reputation: 55340

I like @Ananda's solution. If you'd like to stick with base R:

t(mapply(rbind, table1, table2))

While it's not completely clear what the ultimate goal, I'm guessing you are making multiple calls to table and then looking to have them unified nicely.

it might be easier to use a data.table and then you can simply run

myDT[..., table(<variables>), by=<someFactor>]

Upvotes: 1

A5C1D2H2I1M1N2O1R2T1
A5C1D2H2I1M1N2O1R2T1

Reputation: 193507

Use interleave from the "gdata" package:

> library(gdata)
> interleave(table1, table2)
  A        B       
A "TOP"    "TOP"   
A "BOTTOM" "BOTTOM"
B "TOP"    "TOP"   
B "BOTTOM" "BOTTOM"
C "TOP"    "TOP"   
C "BOTTOM" "BOTTOM"
D "TOP"    "TOP"   
D "BOTTOM" "BOTTOM"

Upvotes: 4

Related Questions