1

I would like to add 3 columns below a data who exist. But the problem is that My first data got 10 column with (id,num, x, xx, xxx, xxx, xxx, .....) and the second data got only 3 column with (id,num, x)

I would like to put the second data in first data and for that I would like to create 7 new column (only NA) to use rbind.

For example I have data:

df1 <- data.frame(id = 1:5, num = 6:10, V1 = 11:15, V2 = 16:20)
df2 <- data.frame(id = 6:10, num = 11:15)

I wanted to get expected output:

   id num V1 V2
1   1   6 11 16
2   2   7 12 17
3   3   8 13 18
4   4   9 14 19
5   5  10 15 20
6   6  11 NA NA
7   7  12 NA NA
8   8  13 NA NA
9   9  14 NA NA
10 10  15 NA NA

I tried to create a matrix with only NA and I research on the net but I found nothing

acylam
  • 18,231
  • 5
  • 36
  • 45

2 Answers2

2

The base R function rbind requires that all data.frames being bind together have the same number of columns and names. This would require either adding the excess columns to the smaller dataframe with NA rows or another function that allows non-matching columns. Fortunately, there is a function called bind_rows from dplyr that does exactly that:

dplyr::bind_rows(df1, df2)

Output:

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

> dplyr::bind_rows(df1, df2)
   id num V1 V2
1   1   6 11 16
2   2   7 12 17
3   3   8 13 18
4   4   9 14 19
5   5  10 15 20
6   6  11 NA NA
7   7  12 NA NA
8   8  13 NA NA
9   9  14 NA NA
10 10  15 NA NA
acylam
  • 18,231
  • 5
  • 36
  • 45
  • @Raph Glad that this helped. If you think that this solution answers your question. Please accept it so others can see. – acylam Feb 07 '19 at 20:03
0

This is an outer join---it just happens to be one where none of the IDs overlap.

merge(df1, df2, all = TRUE)
   id num V1 V2
1   1   6 11 16
2   2   7 12 17
3   3   8 13 18
4   4   9 14 19
5   5  10 15 20
6   6  11 NA NA
7   7  12 NA NA
8   8  13 NA NA
9   9  14 NA NA
10 10  15 NA NA

See the FAQ on how to merge (join) data in R? for context and more options.

Gregor Thomas
  • 136,190
  • 20
  • 167
  • 294
  • 1
    Note that this gives different output than a row bind if `id` and `num` have matching rows. The sample data just happens to not have any overlap for this to work. – acylam Feb 07 '19 at 20:08