Search code examples
rrbind

How to rbind the data with different number of column in R?


I would like to bind the 2 different length of data frame with some constraint but I'm not sure how to do that. After I run the code, it said that "the numbers of columns of arguments do not match".

I would like to bind the two different data frame based on their column names. Based on the sample data below, I would like to have a combined data frame such that the row names of dtf2 become the first column while the first column for dtf1 is still remain as the same. I attached diagram below for the expected output that I want.

The code below is my sample data

a <- c(1,2,3,4,5,6,6,7,7)
b <- c(11,3,6.5,7,8,9,3,2,5)
dtf1 <- as.data.frame(rbind(a,b))
colnames(dtf1) <- c("aa","bb","cc","dd","ee","ff","gg","hh","ii")

c <- c(1,2,3,4,5,6,7,8)
d <-c(10,9,8,7,6,5,4,3)
dtf2 <- as.data.frame(rbind(c,d))
colnames(dtf2) <- c("bb","cc","dd","ee","ff","gg","hh","ii")

rbind(dtf1,dtf2)

This diagram is the expected output that I desire:

enter image description here


Solution

  • You could first cbind the rownames in dtf2 and rbind it with dtf1.

    rbind(dtf1, cbind(aa = rownames(dtf2), dtf2))
    
    #  aa bb  cc dd ee ff gg hh ii
    #a  1  2 3.0  4  5  6  6  7  7
    #b 11  3 6.5  7  8  9  3  2  5
    #c  c  1 2.0  3  4  5  6  7  8
    #d  d 10 9.0  8  7  6  5  4  3
    

    Using dplyr, it doesn't directly coerce the column to character so you need to explicitly mention it.

    library(dplyr)
    bind_rows(dtf1 %>% mutate(aa = as.character(aa)), 
              bind_cols(aa = rownames(dtf2), dtf2))