簡體   English   中英

根據多列的匹配行合並兩個數據幀

[英]merge two data frames based on matching rows of multiple columns

以下是我嘗試合並claimants人和unemp的兩個數據集的摘要和結構,可以在此處找到Claims.csvunemp.csv

 > tbl_df(claimants)
# A tibble: 6,960 × 5
       X       County  Month  Year Claimants
   <int>       <fctr> <fctr> <int>     <int>
1      1      ALAMEDA    Jan  2007     13034
2      2       ALPINE    Jan  2007        12
3      3       AMADOR    Jan  2007       487
4      4        BUTTE    Jan  2007      3496
5      5    CALAVERAS    Jan  2007       644
6      6       COLUSA    Jan  2007      1244
7      7 CONTRA COSTA    Jan  2007      8475
8      8    DEL NORTE    Jan  2007       328
9      9    EL DORADO    Jan  2007      2120
10    10       FRESNO    Jan  2007     19974
# ... with 6,950 more rows


> tbl_df(unemp)
# A tibble: 6,960 × 7
    County  Year Month laborforce emplab unemp unemprate
*    <chr> <int> <chr>      <int>  <int> <int>     <dbl>
1  Alameda  2007   Jan     743100 708300 34800       4.7
2  Alameda  2007   Feb     744800 711000 33800       4.5
3  Alameda  2007   Mar     746600 713200 33300       4.5
4  Alameda  2007   Apr     738200 705800 32400       4.4
5  Alameda  2007   May     739100 707300 31800       4.3
6  Alameda  2007   Jun     744900 709100 35800       4.8
7  Alameda  2007   Jul     749600 710900 38700       5.2
8  Alameda  2007   Aug     746700 709600 37000       5.0
9  Alameda  2007   Sep     748200 712100 36000       4.8
10 Alameda  2007   Oct     749000 713000 36100       4.8
# ... with 6,950 more rows

我以為首先應該將所有factor列更改為character列。

unemp[sapply(unemp, is.factor)] <- lapply(unemp[sapply(unemp, is.factor)], as.character)

claimants[sapply(claimants, is.factor)] <- lapply(claimants[sapply(claimants, is.factor)], as.character)

m <-merge(unemp, claimants, by = c("County", "Month", "Year"))
dim(m)
[1]  0 10

dim(m)的輸出中,結果數據幀中有0行。 所有6960行應彼此唯一匹配。

為了驗證兩個數據框是否具有“ County”,“ Month”和“ Year”這三列的唯一組合,我對數據框中的這些列進行了重新排序和重新排列,如下所示:

a <- claimants[ order(claimants[,"County"], claimants[,"Month"], claimants[,"Year"]), ]

b <- unemp[ order(unemp[,"County"], unemp[,"Month"], unemp[,"Year"]), ]

b[2:4] <- b[c(2,4,3)]
a[2:4] %in% b[2:4]
[1] TRUE TRUE TRUE

最后的輸出確認這兩個數據框中的所有“縣”,“月”和“年”列彼此匹配。

我試圖尋找到的文檔merge ,無法收集我在哪里出問題,我也曾嘗試inner_join從功能dplyr

> m <- inner_join(unemp[2:8], claimants[2:5])
Joining, by = c("County", "Year", "Month")
> dim(m)
[1] 0 8 

我遺漏了一些東西,不知道是什么,將不勝感激,這將有助於理解,我知道我不必必須按三列重新排列行以運行merge R應該標識匹配的行並合並不匹配的列。

索賠人df的縣均大寫,而失業者df的縣均小寫。

在讀取數據時,我使用了options(stringsAsFactors = FALSE)。 一些建議將X列都放在這兩個列中,這似乎沒有用。

options(stringsAsFactors = FALSE)
claims <- read.csv("claims.csv",header=TRUE)
claims$X <- NULL
unemp <- read.csv("unemp.csv",header=TRUE)
unemp$X <- NULL
unemp$County <- toupper(unemp$County)

m <- inner_join(unemp, claims)
dim(m)

# [1] 6960    8

暫無
暫無

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

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