Joining and matching two tables

I have two tables that look like this:

|Year|Month|Day|Hour|
|---|---|---|---|
|2009|1|1|0|
|2009|1|1|1|
|2009|1|1|2|
|2009|1|1|3|
|2009|1|1|4|
|2009|1|1|5|
|2009|1|1|6|
|2009|1|1|7|
|2009|1|1|8|
|2009|1|1|9|
|2009|1|1|10|
|Year|Month|Day|Weekday|Holiday|
|---|---|---|---|---|
|2009|1|1|4|1|
|2009|1|2|5|0|
|2009|1|3|6|0|
|2009|1|4|0|0|

How can I join the Weekday and Holiday columns from Table2 to the Table1 and it fills up values based on table 2? Sorry if this is confusing

I think I figured it out

d3 <- d2 %>%
  separate(Date, into = c("Date", "Time"), sep = " ") %>%
  mutate(Date = as_date(Date))

x <- right_join(d3, c2, by = "Date")

In your original data frame, you had separate columns for year, month and day. With dplyr joins, you can join by multiple columns, eg something like

left_join(df1, df2, by = c(Year, Month, Day))

In fact if you didn't mention a value for the by argument, dplyr joins will look for all identically named variables in both data frames, and join by those. (Thought I'd share just in case you wanted to skip the Date creation step)

2 Likes

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.