2017-02-27 78 views
0

行兩個數據幀下面是兩組數據我試圖合併claimantsunemp的總結和結構,他們可以我這裏找到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行應該唯一匹配。

要驗證這兩個數據幀有3列「縣」的獨特組合,「月」,和「年份」我重新排序和重新排列這些列,如下dataframes內:

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文件,無法收集我在哪裏出了問題,我自己也嘗試從dplyrinner_join功能:

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

我失去了一些東西,不知道是什麼,很感激理解這一點的幫助下,我知道我不應該由三列重新排列行運行merge [R應該找出匹配的行和合並不匹配的列。

+2

ALAMEDA!= Alameda –

回答

1

索賠人df的縣全部大寫,失業df有小寫。

我在讀取數據時使用了選項(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