Q: How to create a new variable in a specific table from multiple conditions in another table I have 2 different tables from 2 different samples, TABLE 1 and TABLE 2(with different number of rows or individuals).  The 2 tables contain the same variables :  AGE (quantitative),  PROVINCE (qualitative with 11 choices), PLACE (urban or rural), AGE AT MARRIAGE, PARITY or number of children (quantitative).
From TABLE 1, I want to create a new variable (PAR_REF) in  TABLE 2 defined as  the average PARITY achieved by an individual from the same PROVINCE , the same PLACE, with the same AGE and with the same AGE AT MARRIAGE as a woman in TABLE 1. I mean, the values for the new variable I want to create(PAR_RF)in TABLE 2 must be the average PARITY for all individuals having the same characteristics (for the variables AGE, PROVINCE, PLACE, AGE AT MARRIAGE)  in TABLE 1.
This is what I want to do

What is the process?

A: On TABLE1, group_by those variables and summarize, then join the result with TABLE2.
However, for this to work, you need in TABLE1 at least one individual of the same province/place/age/age of marriage as every one found in TABLE2, otherwise the join will leave missing values.
library(tidyverse)

TABLE_REF <- TABLE1 %>%
  group_by(AGE, PROVINCE, PLACE, AGE_AT_MARRIAGE) %>%
  summarize(PAR_REF = mean(PARITY)) %>%
  ungroup()

TABLE2 %>% left_join(TABLE_REF, by = c("AGE", "PROVINCE", "PLACE", "AGE_AT_MARRIAGE"))

