Erik Brole
Erik Brole

Reputation: 355

Make a join between dataframes with different types of data

Having a dataframe like this one:

df1 <- data.frame(id = c("id1","id2","id3", "id3"), status = c("open","close","open/close","close"), stock = c("google", "amazon", "yahoo", "amazon"))

the second dataframe:

df2 <- data.frame(id = c("id1","id2", "id2", "id3"), newspaper = c("times", "newyork", "london", "times"))

and the id column is the same between the two dataframe. How is it possible to create a melt/joined dataframe between all case from all columns id, status, stock and newspaper?

Example of expected output:

   id     status  stock newspaper
id1       open google     times
id2      close amazon   newyork
id2      close amazon    london
id3 open/close  yahoo     times
id3      close amazon     times

Upvotes: 0

Views: 52

Answers (2)

diomedesdata
diomedesdata

Reputation: 1075

You can use base R:

merge(df1, df2, by = 'id', all = TRUE)

Upvotes: 1

Jamie
Jamie

Reputation: 1965

If you want everything included you can do a full_join.

For more information on learning how to join tables. Refer here

library(dplyr)
df1 %>%
  full_join(df2, by = "id")
# output
   id     status  stock newspaper
1 id1       open google     times
2 id2      close amazon   newyork
3 id2      close amazon    london
4 id3 open/close  yahoo     times
5 id3      close amazon     times

Upvotes: 2

Related Questions