Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in R Programming by (50.2k points)

I am having two dataframes as the following:

df1=data.frame(col1=c('A', 'A', 'B', 'B', 'B'), col2a=c(1, 4, 3, 2, 5))

df2=data.frame(col1=c('A', 'A', 'A', 'B', 'B'), col2b=c('a', 'd', 'c', 'b', 'e'))

I want to have a resulted df like this:

df3=data.frame(col1=c('A', 'A', 'A', 'A', 'A', 'A', 'B', 'B', 'B', 'B', 'B', 'B),' col2b=c('a', 'a', 'd', 'd', 'c', 'c', 'b', 'b', 'b', 'e', 'e', 'e'), col2a=c(1, 4, 1, 4, 1, 4, 3, 2, 5, 3, 2, 5))

I have tried to execute the merge() for df1 and df2 by column col1 but it doesn't work because col1 is a non-unique column. 

1 Answer

0 votes
by (108k points)

You can perform that using the dplyr package:

dplyr::full_join(df1, df2)

Output

#    col1 col2a col2b

# 1     A     1     a

# 2     A     1     d

# 3     A     1     c

# 4     A     4     a

# 5     A     4     d

# 6     A     4     c

# 7     B     3     b

# 8     B     3     e

# 9     B     2     b

# 10    B     2     e

# 11    B     5     b

# 12    B     5     e

If you want to the same in base R, just write:

merge(df1, df2)

If you are interested in R certification, then do check out the R programming certification.

Browse Categories

...