簡體   English   中英

R:基於匹配多個列將列從一個數據集添加到另一個數據集

[英]R: Adding a column from one dataset to another based on matching multiple columns

我有兩個數據集:

DS1 - 包含一個主題列表,其中包含姓名、身份證號和就業狀態列

DS2 - 包含相同的主題名稱和 ID 號列表,但其中一些在第二個數據集中缺失。
最后,它包含教育水平的第三列。

我想將 Education 列合並到第一個數據集上。 我已經使用合並 function 按 ID 號排序來完成此操作,但由於第二個數據集上缺少一些 ID 號,我想按名稱合並剩余的教育級別作為次要選項。 有沒有辦法使用 dplyr/tidyverse 做到這一點?

有兩種方法可以做到這一點。 根據您的喜好選擇一種。

第一個選項:

#here I left join twice and select columns each time to ensure there is no duplication like '.x' '.y'
finalDf = DS1 %>% 
  dplyr::left_join(DS2 %>% 
                     dplyr::select(ID,EducationLevel1=EducationLevel),by=c('ID')) %>% 
  dplyr::left_join(DS2 %>% 
                     dplyr::select(Name,EducationLevel2=EducationLevel),by=c('Name')) %>% 
  dplyr::mutate(FinalEducationLevel = ifelse(is.na(EducationLevel1),EducationLevel2,EducationLevel1))

第二個選項:

#first find the IDs which are present in the 2nd dataset

commonIds = DS1 %>% 
  dplyr::inner_join(DS2 %>% 
                      dplyr::select(ID,EducationLevel),by=c('ID'))

#now the records where ID was not present in DS2

idsNotPresent = DS1 %>% 
  dplyr::filter(!ID %in% commonIds$ID) %>% 
  dplyr::left_join(DS2 %>% 
                     dplyr::select(Name,EducationLevel),by=c('Name'))

#bind these two dfs to get the final df

finalDf = bind_rows(commonIds,idsNotPresent)

讓我知道這個是否奏效。

對我來說,臨時程序員的回答工作者中的第二個選項。 太感謝了。 不得不為我的實際數據集使用它,但基本結構工作得很好,而且很容易適應

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM