0

How to simply "paste" two data frames next to each other, filling unequal rows with NAs (e.g. because I want to make a "kable" or sth similar)?

df1 <- data.frame(a = c(1,2,3),
                  b = c(3,4,5))

df2 <- data.frame(a = c(4,5),
                  b = c(5,6))

# The desired "merge"

a b a b
1 3 4 5
2 4 5 6
3 5 NA NA
s_baldur
  • 29,441
  • 4
  • 36
  • 69
persephone
  • 380
  • 2
  • 10
  • Have you tried solutions from this post? https://stackoverflow.com/questions/3699405/how-to-cbind-or-rbind-different-lengths-vectors-without-repeating-the-elements-o – Ronak Shah Dec 03 '20 at 07:55

2 Answers2

0

Thanks to Ronak Shah, I found an easy answer in the answers to this post: How to cbind or rbind different lengths vectors without repeating the elements of the shorter vectors?

Without having to hack anything together, one can use cbind.na from the qpcR: package:

df1 <- data.frame(a = c(1,2,3),
                  b = c(3,4,5))

df2 <- data.frame(a = c(4,5),
                  b = c(5,6))

comb <- qpcR:::cbind.na(df1, df2)

As this answer is 4 years old, I wonder if there are more "modern" solutions in the popular packages like tidyverse et. al.

persephone
  • 380
  • 2
  • 10
0

In base R you could do:

nr <- max(nrow(df1), nrow(df2))
cbind(df1[1:nr, ], df2[1:nr, ])
#   a b  a  b
# 1 1 3  4  5
# 2 2 4  5  6
# 3 3 5 NA NA
s_baldur
  • 29,441
  • 4
  • 36
  • 69