Demi_K Demi_K - 22 days ago 11
R Question

cbind different length of data frames based on column

I have 2 dataframes:

df1
name stock_1 stock_2
A 11 12
B 9 2
C 1 3

df2
name stock_1
D 2
E 4


expected output:

name stock_1 stock_2
A 11 12
B 9 2
C 1 3
D 2 NA
E 4 NA


the name and stock_1 names of columns. I try to cbind the 2 df but it is not working. Is there any efficient way?

Answer

We could use dplyr::full_join() :

library(dplyr)
df3 <- full_join(df1, df2)
df3
  name stock_1 stock_2
1    A      11      12
2    B       9       2
3    C       1       3
4    D       2      NA
5    E       4      NA
Comments