Search code examples
rdataframecbind

How to cbind data.frames with differing lengths without knowing the lengths of the data.frames


I am hoping to find a way to cbind data.frames with differing lengths, but I want to cbind the data.frames without having to specify the lengths. As the lengths of the data.frames I will be working with will vary I do not want to find the lengths before I use a cbind.

Current Error I am receiving

Error in data.frame(..., check.names = FALSE) : 
  arguments imply differing number of rows: 8, 10

Desired Output with blank

         A B
rwone    1 2
rwtwo    2 2
rwthree    3

Desired Output with NA

         A  B
rwone    1  2
rwtwo    2  2
rwthree  NA 3

I have tried.

length(A) = length(B)

cbind(A,B)

I have also tried.

if(length(A)<length(B)) {
     if(first==1) A = c(rep(NA, length(B)-length(A)),A);B=B
     if(first==0) A = c(A,rep(NA, length(B)-length(A)));B=B
} 

if(length(B)<length(A)) {
     if(first==1) B = c(rep(NA, length(A)-length(B)),B);A=A
     if(first==0) B = c(y,rep(NA, length(A)-length(B)));A=A
} 

cbind(A,B)

Any help would be very much appreciated.

Dre


Solution

  • Merge is most straightforward when you're merging on a column of a dataframe as opposed to the rownames. If you assign a column in both dataframes to be the same as the rownames, then merge should work. This worked for me:

    A = data.frame(A = c(1, 2))
    B = data.frame(B = c(2,2,3))
    A$key = row.names(A)
    B$key = row.names(B)
    
    merge(A, B, all = TRUE)
    

    You could also use join from the plyr library.

    library(plyr)
    join(A, B, by = "key", type = "full")