Home > Enterprise >  Combine two multi-column dataframes into single two-column dataframe
Combine two multi-column dataframes into single two-column dataframe

Time:11-24

I have two dataframes looking like:

Sheet1:

Column A Column B
Sample1 Sample2
Sample3 Sample4

Sheet2:

Column A Column B
abcd efgh
ijkl mnop

I want to combine them together into

Column A Column B
Sample1 abcd
Sample2 efgh

etc.

Basically each cell of the two sheets matches just want to put them into a single file.

CodePudding user response:

Base R solution using stack() within data.frame():

combined <- data.frame(
  Column.A = stack(Sheet1)[, 1], 
  Column.B = stack(Sheet2)[, 1]
)

combined <- combined[order(combined$Column.A), ]
combined
  Column.A Column.B
1  Sample1     abcd
3  Sample2     efgh
2  Sample3     ijkl
4  Sample4     mnop

Or a slight variation using cbind() instead of data.frame():

combined <- cbind(
  stack(Sheet1)[, 1, drop = FALSE], 
  stack(Sheet2)[, 1, drop = FALSE]
)

names(combined) <- names(Sheet1)
combined <- combined[order(combined$`Column A`), ]
  Column A Column B
1  Sample1     abcd
3  Sample2     efgh
2  Sample3     ijkl
4  Sample4     mnop
  •  Tags:  
  • r
  • Related