选出数据集

birthdays <- read.csv("https://raw.githubusercontent.com/higgi13425/medicaldata/master/data-raw/join_data/birthdays.csv") %>% select(-X)

hometowns <- read.csv("https://raw.githubusercontent.com/higgi13425/medicaldata/master/data-raw/join_data/hometowns.csv") %>% select(-X)

检查数据集,准备left join合并

glimpse(birthdays)
## Rows: 3
## Columns: 2
## $ name <chr> "Rudolf Virchow", "Virginia Apgar", "William Osler"
## $ dob  <chr> "10/13/1821", "6/7/1909", "7/12/1849"
glimpse(hometowns)
## Rows: 3
## Columns: 2
## $ name     <chr> "Rudolf Virchow", "Virginia Apgar", "Hippocrates"
## $ hometown <chr> "Berlin", "Westfield, NJ", "Kos"
left_join(x = hometowns, y = birthdays)
## Joining with `by = join_by(name)`
##             name      hometown        dob
## 1 Rudolf Virchow        Berlin 10/13/1821
## 2 Virginia Apgar Westfield, NJ   6/7/1909
## 3    Hippocrates           Kos       <NA>
##用指定variable精确合并
left_join(x = hometowns, y = birthdays, by = "name")
##             name      hometown        dob
## 1 Rudolf Virchow        Berlin 10/13/1821
## 2 Virginia Apgar Westfield, NJ   6/7/1909
## 3    Hippocrates           Kos       <NA>

right joins 合并

right_join(x = hometowns, y = birthdays)
## Joining with `by = join_by(name)`
##             name      hometown        dob
## 1 Rudolf Virchow        Berlin 10/13/1821
## 2 Virginia Apgar Westfield, NJ   6/7/1909
## 3  William Osler          <NA>  7/12/1849
hometowns2 <- read.csv("https://raw.githubusercontent.com/higgi13425/medicaldata/master/data-raw/join_data/hometowns2.csv") %>% 
  select(-X) %>% 
  purrr::set_names(c("name", "hometown"))
hometowns2 %>% 
  right_join(birthdays)
## Joining with `by = join_by(name)`
##             name      hometown        dob
## 1 Rudolf Virchow        Berlin 10/13/1821
## 2 Virginia Apgar Westfield, NJ   6/7/1909
## 3  William Osler          <NA>  7/12/1849

inner joins和full joins

inner_join(x = hometowns, y =birthdays)
## Joining with `by = join_by(name)`
##             name      hometown        dob
## 1 Rudolf Virchow        Berlin 10/13/1821
## 2 Virginia Apgar Westfield, NJ   6/7/1909
full_join(x = hometowns, y =birthdays)
## Joining with `by = join_by(name)`
##             name      hometown        dob
## 1 Rudolf Virchow        Berlin 10/13/1821
## 2 Virginia Apgar Westfield, NJ   6/7/1909
## 3    Hippocrates           Kos       <NA>
## 4  William Osler          <NA>  7/12/1849