0

Some example data of stucture:

df1 = data.frame(x=c('a', 'b', 'c', 'd', 'e'))
df2 = data.frame(x=c('f', 'g', 'h'),y = c(0,1,0))
df3 = data.frame(x=c('i', 'j','k','l'), y = c(1,7,5,2,6), z = c(75,3,25,2,1))

I have 3 different dataframes.

df1 has 22201 object and 121 variables df2 has 8403 object and 68 variables df3 has 50476 object and 157 variables

I try to merge them using merge and I receive this error:

Error in fix.by(by.x, x) : 
  'by' must specify one or more columns as numbers, names or logical

using cbind and I received this error:

Error in data.frame(..., check.names = FALSE) : 
  arguments imply differing number of rows: 22201, 8403, 50476

and rbind and I receive this error:

Error in rbind(deparse.level, ...) : 
  numbers of columns of arguments do not match

How can I merge dataframes with different number of rows and columns? I have to refer that columns have the same names in dataframes so in the merge I expect the number of columns be the highest numbers of columns of the dataframe which contains the most.

1
  • Can you show us your code and a reproducible example of your dataframes? Commented Nov 14, 2017 at 14:37

2 Answers 2

3

In this case, use rbind.fill from the library plyr

library(plyr)
rbind.fill(df1, df2, df3)

This will merge all your 3 data frames with different number of columns.

Sign up to request clarification or add additional context in comments.

Comments

2

dplyr is an evolution from plyr, so I'd use it instead. bind_rows will achieve what you want:

library(dplyr)
bind_rows(df1, df2, df3, ...)

One example:

tbl1 <- data_frame(var1 = c('a', 'b', 'c'),
                   var2 = c('x', 'y', 'z'))

tbl2 <- data_frame(var1 = c('e', 'd', 'g', 'h'))

tbl3 <- data_frame(var6 = 1, 
                   var10 = 14)

> bind_rows(tbl1, tbl2, tbl3)
# A tibble: 8 x 4
   var1  var2  var6 var10
  <chr> <chr> <dbl> <dbl>
1     a     x    NA    NA
2     b     y    NA    NA
3     c     z    NA    NA
4     e  <NA>    NA    NA
5     d  <NA>    NA    NA
6     g  <NA>    NA    NA
7     h  <NA>    NA    NA
8  <NA>  <NA>     1    14

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.