2017-12-27 137 views
0

我需要合併兩個數據集,但在第二個數據集中,可能有重複的id,例如多個id爲1,1,1。如果有重複的ID,如何合併到它們的第一行?合併兩個數據集只有第一行R

更清楚,這裏有一個重複的例子:

df1 
structure(list(id = 1:2, y = 10:11), .Names = c("id", "y"), class = "data.frame", row.names = c(NA, 
-2L)) 

df2 
structure(list(id = c(1L, 1L, 1L, 2L), x1 = 435:438, x2 = c(435L, 
436L, 436L, 438L), x3 = c(435L, 436L, 436L, 438L)), .Names = c("id", 
"x1", "x2", "x3"), class = "data.frame", row.names = c(NA, -4L 
)) 

Eaxample:在輸出我希望這種格式

id y x1 x2 x3 
1 10 435 435 435 
2 11 438 438 438 

I.E. 2行和3行(1個ID)不參與合併。

回答

1

您可以使用data.table來完成。您只能保留第一次出現的位置,其中第二個數據集爲id == 1,然後merge兩個數據集。

這裏是解決方案:

library(data.table) 
setDT(df2) 
df2[, idx := 1:.N, by = id] 
df2 <- df2[idx == 1, ] 
df2[, idx := NULL] 
output <- merge(df1, df2, by = "id") 
output 

它會給你你需要的輸出:

id y x1 x2 x3 
1 1 10 435 435 435 
2 2 11 438 438 438