1

I want to combine multiple dataframes of unequal length into a new dataframe that has NA values for empty rows.

e.g. df1

A
1
2
3
4
5

df2
B
1
2
3
4
5
6

Desired output

df3
A  B
1  1
2  2
3  3
4  4
5  5
NA 6

I tired a cbind() but that gives me an error.

Rn00b
  • 11
  • 2

1 Answers1

0

Try

df1 <- data.frame(A = 1:5)
df1$id <- row.names(df1)
df2 <- data.frame(B = 1:6)
df2$id <- row.names(df2)
merge(df1, df2, all = T, by = "id")
  id  A B
1  1  1 1
2  2  2 2
3  3  3 3
4  4  4 4
5  5  5 5
6  6 NA 6

For situations like this, it is useful to familiarize yourself with all the different kinds of joins that you can do.

coffeinjunky
  • 11,254
  • 39
  • 57
  • Thank you so much. Do you have recommendations for a thread on joins ? – Rn00b Jul 28 '18 at 03:37
  • @Rn00b I have edited my answer to give you a link. If this answers your question, feel free to accept this answer. If you find it particularly helpful, you can also upvote it. – coffeinjunky Jul 28 '18 at 09:10